Table-driven testing in action
Now that we have discussed the fundamentals of identifying edge cases and handling errors, we can begin to look at how to build test suites that cover a variety of scenarios. A popular technique in Go is to use table-driven testing. This technique uses the fundamentals we’ve learned so far to structure test suites that cover a variety of scenarios.
Let us begin with a simple example to demonstrate the test-writing process. We will implement a new Divide
mathematical operation that does the following:
- Returns the result formatted as a string to two decimal points
- Returns an error in the case that the divisor is 0
From the preceding requirement, we can formulate the following signature for this new operation:
func Divide(x, y int8) (*string, error)
We remember that the minimum value of int8
is –128
and the maximum value is 127
.
As previously discussed, we make use of multiple return values to encourage explicit...