A common way of writing tests in Go: Table Driven Test

It is very often to have lots of repetitive code when writing a test. Table driven test provides a way to easily iterate through all table entries to perform the check. Each table entry includes the desired input and output of the function. Here is an simple example from the testing code for the fmt package:


In this case, adding a test is just adding a line in the struct with input and expected output, which reduces the unnecessary duplication.
Though it’s convenient to use this method, there is one notable tip: it is important to write detailed error message for each test case and specify which test case it is in error message, since we do not have names for each test. In this case it will be easy to know which test case fails and why.

More details and examples about table driven test are provided in the below links.
https://github.com/golang/go/wiki/TableDrivenTests
https://blog.golang.org/subtests
https://dave.cheney.net/2019/05/07/prefer-table-driven-tests