Home >Backend Development >Golang >How to test Golang functions using unit testing framework?
Use the unit testing framework for unit testing in Go: import the testing package. Write unit test functions prefixed with Test. Use assertion functions such as assertEqual() to verify test results. Run the unit test (go test) to verify the correctness of the function.
How to use the unit testing framework to test Go functions
Unit testing is essential to verify the correctness of a single function or method Important software development practices. In Go, unit testing is very simple using a unit testing framework such as the testing
package.
Install the unit testing framework
#testing
package is part of the Go standard library. To use it, import the testing
package into your project:
import "testing"
Writing Unit Tests
Each unit test is a Test
is the function prefixed. It accepts a pointer *testing.T
as a parameter, which is used to report test results and record failure information.
The basic unit testing function is as follows:
func TestAdd(t *testing.T) { result := Add(1, 2) if result != 3 { t.Errorf("Add(1, 2) = %d; want 3", result) } }
Assertion
##testing The package provides a series of assertion functions, Used to verify test results. Commonly used assertions include:
Practical case
Consider a function that calculates the sum of two numbersAdd() Function:
func Add(a, b int) int { return a + b }We can write a unit test to verify this function:
import "testing" func TestAdd(t *testing.T) { tests := []struct { a, b, want int }{ {1, 2, 3}, {0, 0, 0}, {-1, -1, -2}, } for _, test := range tests { result := Add(test.a, test.b) if result != test.want { t.Errorf("Add(%d, %d) = %d; want %d", test.a, test.b, result, test.want) } } }
Run the test
To run unit tests, use thego test command. It will find and run all
Test* functions in the project.
go testIf the test passes, it will output the following results:
PASS ok my_project/my_package 1.730sOtherwise, it will report the failed test, including an error message.
The above is the detailed content of How to test Golang functions using unit testing framework?. For more information, please follow other related articles on the PHP Chinese website!