This is a general case around Test Data in the Test Smells.
Let’s have a look at a test snippet:
What does this test tell us?
Here’s what I think it tells me:
- There is a
- It has a
- We’re looking at the output of that method
- We’re asserting on equality
Structurally, these is a perfectly clean test. It’s missing one vital ingredient though…
What The Hell Is The Use Case!?
The difficulty here is that you can’t see what the code under test is supposed to do from the test itself.
Comparatively, from this one assertion:
You can probably guess that the
StringWrangler, whatever that is, alternately capitalizes letters in a string.
Don’t Make The Test Data Obscure
This is where we have conflicting priorities writing code for tests. On the one hand, we feel like we should extract constants to represent magic values. On the other hand, by doing so, the assertions/execution code in our tests starts to look particularly cryptic.
If the original example were written:
Ignore the made up Time type here.
We can understand with a minimum of guesswork how this code must surely operate.
Tests are an important piece of documentation about your code. Test data should be simple, concrete and visible.
Hiding data behind a badly named constant won’t do.
It’s hard to name a constant well!
As data gets more complex, or reused, it’s necessary to consider methods like test data factories or constants, or even data files. However, the principle to focus on is how well the test explains the use case being tested.