Read Before: Understaing Unit Test In short, unit tests are codes focusing on a small part of the software system.
After understanding why developers needs to write unit tests, let's Go.
Go Official The official package of Go is here
// example_test.go File name must endup with `_test`
import "testing" // This is the package to import
func TestMyLogic(t *testing.T) { // Function name should start with word `Test` followed by a capital letter `My`
// <setup code>
t.Run("TestCase=A", func(t *testing.T) { ... }) // Subtest to test many usecases of the function.
...
t.Run("TestCase=X", func(t *testing.T) { ... })
// <tear-down code>
}
Commands to run the tests go test -run '' # Run all tests. go test -run MyLogic # Run top-level tests matching "Foo", such as "TestFooBar". go test -run Mylogic/TestCase=A # For top-level tests matching "Foo", run subtests matching "A=". go test -run /TestCase=A # For all top-level tests, run subtests matching "A=1".
There are a lot of few frameworks built in Go to help developers become productive. I will list them here and write examples in separate files.