Home  >  Article  >  Backend Development  >  Combination of error handling and unit testing of golang functions

Combination of error handling and unit testing of golang functions

王林
王林Original
2024-04-24 17:36:02828browse

Error handling in GoLang uses the error type to represent errors, which can be created through fmt.Errorf(). Unit testing uses the testing library to verify the correctness of the function by writing test cases and assert whether the returned results are consistent with expectations.

Combination of error handling and unit testing of golang functions

GoLang function error handling and unit testing

Error handling

## The error handling mechanism in #GoLang is very simple and effective. By using the

error type we can represent errors in function execution. Error messages can be created through the fmt.Errorf() function.

package main

import (
    "fmt"
)

func divide(a, b int) (int, error) {
    if b == 0 {
        return 0, fmt.Errorf("cannot divide by zero")
    }
    return a / b, nil
}

func main() {
    result, err := divide(10, 2)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(result)
    }
}

Unit testing

Unit testing is crucial to verify the correctness of the function. GoLang provides

testing libraries to easily write and run unit tests.

package main

import (
    "fmt"
    "testing"
)

func TestDivide(t *testing.T) {
    type testCases struct {
        a int
        b int
        expected int
        expectedError error
    }

    cases := []testCases{
        {10, 2, 5, nil},
        {10, 0, 0, fmt.Errorf("cannot divide by zero")},
    }

    for _, c := range cases {
        result, err := divide(c.a, c.b)
        if result != c.expected || err != c.expectedError {
            t.Errorf("Test failed for input (%d, %d) expected (%d, %s) but got (%d, %s)", c.a, c.b, c.expected, c.expectedError, result, err)
        }
    }
}

In this example, we have created a test table containing different test cases. We then run the

divide function against each test case and assert that the returned values ​​and errors match the expected results.

By combining error handling with unit testing, we can ensure that functions work as expected under a variety of input situations.

The above is the detailed content of Combination of error handling and unit testing of golang functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn