Unit Testing
https://blog.jetbrains.com/go/2022/11/22/comprehensive-guide-to-testing-in-go
How to do unit testing
Create file
project_test.goThe test function signature is
TestXXX(t *testing.T)
Those two steps are the only mandatory step to create unit testing. But we can follow some best practices to structure our tests and test cases:
Structure our test as test tables with many test cases
Properly assert the function behavior
Name test cases as descriptive as possible
Useful Commands
Use
go test -race ./...to run the unit test with a check for a race conditionUse
go tool cover -func=coverage.outto display coverage information on the terminal consoleUse
go tool cover -html=coverage.outto display the coverage information on HTML format in browser.
Examples
package main
import "strconv"
// If the number is divisible by 3, write "Foo" otherwise, the number
func Fooer(input int) string {
isfoo := (input % 3) == 0
if isfoo {
return "Foo"
}
return strconv.Itoa(input)
}project_test.go
Table Driven testing
Errors and Logs
Running Parallel Tests
The following code will test Fooer(3) and Fooer(7) at the same time
Skipping Tests
Last updated
Was this helpful?