Unit testing and mocks
As we explained, a unit test is about verifying one specific part of the code in isolation. In Go, we have a testing framework built in, so we don’t need to do anything to actually start testing.
Let’s begin with an elementary example:
func Add(a, b int) int {
return a + b
}
func TestAdd(t *testing.T) {
got := Add(1, 2)
want := 3
if got != want {
t.Errorf("Add(1, 2) = %d; want %d", got, want)
}
}
In this case, we define an Add function that adds two numbers and returns the result. Right after the Add function, we define the TestAdd function, responsible for testing the Add function. In Go, there is a well-known pattern for testing: the got/want pattern – we set a want variable to the value that we expect to happen on the function execution, then we execute the function and store the result in the got variable. Then, we check if they match. If they don’t, we will use t.Errorf to report the error...