Writing functional test cases in Go involves using the testing package, which provides functions for defining test cases (func Test) and reporting failures (t.Error). Unit tests test individual functions in isolation, while integration tests focus on interactions with other components. The sample test cases show how to use the testing package to define test functions, define input and output test cases, verify the results, and run them using the go test command.
When writing Go code, writing test cases is crucial to ensure that the code is robust and correct. Below is a guide to writing functional test cases, including practical examples using the Go language.
1. Unit Testing vs Integration Testing
When testing functions, there are two main types:
2. Using Go’stesting
package
The standard library in the Go language for writing test cases istesting
Bag. This package provides some useful functions and types, such as:
func Test(t *testing.T)
: Define a test case.t.Error()
: Report test failure.t.Fail()
: Fail the test immediately.t.Skip()
: Skip the current test.3. Write a test case
The following is an example of writing a function test case:
package main import "testing" // myFunc 是要测试的函数 func myFunc(x int) int { return x * x } // TestMyFunc 测试 myFunc 函数 func TestMyFunc(t *testing.T) { // 定义测试用例 tests := []struct { input int expected int }{ {0, 0}, {1, 1}, {2, 4}, {3, 9}, {-1, 1}, } for _, tc := range tests { // 调用正在测试的函数 result := myFunc(tc.input) // 验证结果 if result != tc.expected { t.Errorf("Test failed. Expected: %d, Got: %d", tc.expected, result) } } }
4. Run Test case
You can use the following command to run the test case:
go test
5. Practical case
Consider a calculation that calculates the sum of elements in a list Function:
func sum(nums []int) int { sum := 0 for _, num := range nums { sum += num } return sum }
The following are some test cases:
func TestSum(t *testing.T) { tests := []struct { input []int expected int }{ {[]int{}, 0}, {[]int{1}, 1}, {[]int{1, 2}, 3}, {[]int{1, 2, 3}, 6}, {[]int{-1, 0, 1}, 0}, } for _, tc := range tests { result := sum(tc.input) if result != tc.expected { t.Errorf("Test failed. Expected: %d, Got: %d", tc.expected, result) } } }
The above is the detailed content of How to write test cases for golang functions?. For more information, please follow other related articles on the PHP Chinese website!