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.
GoLang function error handling and unit testing
Error handling
## The error handling mechanism in #GoLang is very simple and effective. By using theerror 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 providestesting 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) } } }
divide function against each test case and assert that the returned values and errors match the expected results.
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!