Testing in Go
Go has a built-in testing package that provides a framework for writing and running tests.
You can write tests for your Go code by creating files with names that end in _test.go and using functions with names that begin with Test.
func TestAdd(t *testing.T) {
result := add(2, 3)
if result != 5 {
t.Errorf("Expected add(2, 3) to equal 5, but got %d", result)
}
}
In this example, we define a test function called TestAdd that tests the add() function. We use the t.Errorf() function to report an error if the result of the add() function is not equal to 5.
To run the tests, you can use the go test command.
$ go test
PASS
ok example.com/foo 0.002s
In this example, we run the tests for the package located in the directory example.com/foo. The output shows that the tests passed and took 0.002 seconds to run.
No comments:
Post a Comment