(no title)
arsham | 7 years ago
1. I'm not against test libraries/frameworks. In fact I've used Ginkgo and it is fantastic. Some people have came up with clever ways to create those lib/frameworks, but learning another library doesn't come close to enhancing your ability to write better tests.
2. Repetition is the nature of writing tests. In fact, the more you write the same code for testing different parts of the logic, the more strong your API will get. I mean when you make a mistake, you will break more tests. The drawback is you need to know the API well, otherwise you'll face refactoring hell.
3. The more you get near to standard library in general, the more new-comers to your code understand it. You cannot assume everyone knows the library you use in your code, but you can be sure if they are reading your tests, they know a bit of Go and that is quite enough.
4. Table driven tests help with reducing repetition and is so much fun. You can also add more test cases in only one line in the future if you need to. Here is my take on testing the code in the article:
func TestOperations(t *testing.T) {
tcs := []struct {
name string
a, b int
f func(int, int) int
want int
}{
{"Add 1 2", 1, 2, tmp.Add, 3},
{"Subtract 5 3", 5, 3, tmp.Subtract, 2},
{"Multiply 5 6", 5, 6, tmp.Multiply, 30},
}
for _, tc := range tcs {
t.Run(tc.name, func(t *testing.T) {
result := tc.f(tc.a, tc.b)
if result != tc.want {
t.Errorf("result = %d, want %d", result, tc.want)
}
})
}
}
Of course this is for a trivial program. In real world you find yourself test more complex functions and you will create one Test... function for each function.5. The happy path of tests in BDD style frameworks are indented way too much. This distracts you a bit from the test logic.
Thanks for sharing this awesome article.
No comments yet.