Home >Backend Development >Golang >Unit testing of golang functions
Unit tests test individual functions or small pieces of logic to ensure that modified code still runs as expected. Practical examples include writing functions, creating test files, defining test cases, and reporting test failures using t.Errorf. Best practices include writing tests for every function, using meaningful test case names, testing a variety of inputs, running tests frequently, and keeping tests simple.
Unit testing is the process of testing a single function or small piece of logic in a code base . They help ensure that code still runs as expected after modification and reduce the risk of introducing bugs.
Consider the following function, which calculates the sum of two numbers:
func Sum(a, b int) int { return a + b }
To test this function, we can create a test file and use testing
Package:
import ( "testing" ) func TestSum(t *testing.T) { // 创建测试用例 testCases := []struct { a, b, expected int }{ {1, 2, 3}, {3, 5, 8}, {-1, -2, -3}, } for _, tc := range testCases { // 运行函数并获取结果 result := Sum(tc.a, tc.b) // 检查结果是否等于预期值 if result != tc.expected { t.Errorf("预期 %d,但得到 %d", tc.expected, result) } } }
Compile and run the tests using the following command:
go test
If all tests pass, you will see output like this:
PASS ok github.com/username/mypackage 0.004s
t.Errorf
to report test failures. The above is the detailed content of Unit testing of golang functions. For more information, please follow other related articles on the PHP Chinese website!