(no title)
marwatk | 3 years ago
if got == nil {
t.Errorf("blog post was nil, want not-nil")
}
Better than assert.NotNil(t, got, "blog post")
? They seem to suggest that you lose context, but their "Good" examples are similarly devoid of context.
Beltalowda|3 years ago
For example for a simple string comparison it's 12 lines:
vs. 2 lines with a "normal" test: With your NotNil() example it's 4 lines, which seems about 3 lines more than needed.This kind of stuff really adds up if you have maybe 3 or 4 test failures.
jrockway|3 years ago
I've seen a lot of gore in code that uses assertion libraries like assert.Equals(t, int64(math.Round(got)), int64(42)). Consider the error message in that case when got is NaN or Inf.
It is so easy to write your own assertions. I can type them in my sleep and in seconds:
Why implement a NotEquals function when != is built into the language?(The most popular assertion library also inverts the order of got and want, breaking the stylistic convention. It's so bad. Beware of libraries from people that wrote them as their first Go project after switching to Go from Java. There are a lot of them out there, and they are popular, and they are bad.)
Finally, cmp.Diff is the way to go for complex comparisons. Most use of assertion libraries can be replaced by cmp.Diff. I wouldn't use it for simple primitive type equality, but for complex data structures, it's great. And very configurable, so you never have to "settle" for too much strictness or looseness.
dgunay|3 years ago
> Complex assertion functions often do not provide useful failure messages and context that exists within the test function.
I think the best compromise is to avoid combining individual logical units into one assertion. For example:
Bad:
Good: Real world example: at my workplace we have some code that tests HTTP request formation for correctness (right URL, body, headers, etc). Replacing big all-or-nothing booleans with individual assertions on each property of the request provides much more useful test failure messages.As with any published "best practices" like this, have an open mind but don't just cargo cult whatever Google does. Best to be selective about what does and doesn't work for your situation.
adamwk|3 years ago
(One thing I absolutely abhor is those assertion DSLs similar to rspec)