Go Function Testing Guide: Unit testing is used to test function behavior in isolation. testify/assert provides useful assertion tools and needs to be imported github.com/stretchr/testify/assert. Use assert.Equal(t, expected value, function call) to assert. Run the test using the go test command.
Unit testing is crucial when writing Go programs, allowing us to verify that functions run as expected. This article provides a step-by-step guide on how to test Go functions, complete with practical examples.
Unit testing is testing the behavior of a function in an isolated environment, without regard to other code.
testify/assert is a popular Go testing package with a set of useful assertion tools. To install it, run:
go get github.com/stretchr/testify/assert
To use assert, you first need to import it in your unit test file:
import "github.com/stretchr/testify/assert"
Now you can write your test cases as follows:
func TestAdd(t *testing.T) { // 断言 a+b 等于 c assert.Equal(t, 3, Add(1, 2)) }
To run unit tests, use the go test
command on the command line:
go test
Consider The following simple function is used to calculate the sum of two numbers:
func Add(a, b int) int { return a + b }
To test this function, we can use the following test case:
func TestAdd(t *testing.T) { testCases := []struct { a, b, expected int }{ {1, 2, 3}, {5, 10, 15}, {-1, -2, -3}, } for _, tc := range testCases { actual := Add(tc.a, tc.b) assert.Equal(t, tc.expected, actual) } }
In the test case, we combine multiple test sets to the testCases
fragment. Each test case specifies the input values a
and b
, and the expected result expected
.
Loop through each test case, calling the Add
function and using assert to assert that the result matches the expected value. If any assertion fails, the test will fail.
The above is the detailed content of How to test Golang functions?. For more information, please follow other related articles on the PHP Chinese website!