Testing Go Code
January 1, 2020
Notes From: https://nathanleclaire.com/blog/2015/10/10/interfaces-and-composition-for-effective-unit-testing-in-golang/
The important concepts to know are:
- use interfaces
- Construct higher-level interfaces through composition
- Become famiar with go test and the testing module
Interfaces
Using interfaces let you define a set of methods a type (often struct) must define to be considered an implementation of that interface
When any given type implements all the methods of that interface the Go compiler automatically knows that it is allowed to be used as that type.
One can wrap operations which are outside the scope of a given test in an interface and selectively re-implement them for the relevant tests.
Composisiton
You need more then interfaces, the next thing is composition
go test and testing
- For any file foo.go the test is placed in foo_test.go
- go test . runs the unit tests in the currect directory.
- go test ./… will run the tests in the cwd and every directory underneath it.
- go test foo_test.go will file because the file under test is not included in it.
- Tests are functions which accept testing.T struct pointer as an arguement and are idomatically called TestFoo, where Foo is the name of the function being tested.
- You usually do not assert that conditions you expect are true like you may be accustomed to; rather you fail the test by calling t.Fatal if you encounter conditions which are different than you expect.
- Dipslaying output in tests may not work how you expect, use the t.Log and/or t.Logf methods.