Home > Article > Backend Development > Practical tutorial on unit testing of golang functions
Go language unit testing method: import the testing package and the package under test. Define test functions starting with "Test". Define test cases, including parameters and expected results. Iterate over the test cases, call functions and compare actual results with expected results. If there is a difference, the trigger test fails.
Practical tutorial on unit testing of Go functions
Unit testing is an indispensable part of software development, it can help us Ensure code correctness and reduce defects. In Go, you can write unit tests using the built-in testing
package.
Code Example
Suppose we have a greetPackage
package that contains a function named Greet
that Accepts a name parameter and returns a greeting.
package greetPackage import "fmt" func Greet(name string) string { return fmt.Sprintf("Hello, %s!", name) }
We can use the testing
package to write a unit test to test the functionality of the Greet
function.
package greetPackage_test import ( "testing" "github.com/example/myproject/greetPackage" ) func TestGreet(t *testing.T) { tests := []struct { name string expected string }{ {"Alice", "Hello, Alice!"}, {"Bob", "Hello, Bob!"}, } for _, test := range tests { actual := greetPackage.Greet(test.name) if actual != test.expected { t.Errorf("Greet(%s) = %s; expected %s", test.name, actual, test.expected) } } }
How it works
testing
package and the package being tested (greetPackage
). *testing.T
parameter. tests
variable to define a test case slice, where each case contains the parameters to be tested (name
) and the expected results (expected
) . for
loop to traverse the test cases in sequence and call the greetPackage.Greet
function. actual
) of the greetPackage.Greet
function to the expected result (expected
) and raise a ## if they are different #t.Error.
Run the test
Run the test by running the following command in the terminal:go test -v github.com/example/myproject/greetPackageIf the test is successful, it will output the following information:
PASS ok github.com/example/myproject/greetPackage 0.004s
The above is the detailed content of Practical tutorial on unit testing of golang functions. For more information, please follow other related articles on the PHP Chinese website!