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

Combination of error handling and unit testing of golang functions

王林
Release: 2024-04-24 17:36:02
Original
879 people have browsed it

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)
    }
}
Copy after login

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)
        }
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template