This is a general case around Test Data in the Test Smells.
Letโs have a look at a test snippet:
1 2 3 4 5 | @Testvoid dayPercentile() { assertThat(DayPercentileCalculator.calculate(EXAMPLE_1)) .isEqualTo(EXAMPLE1_EXPECTED);} |
What does this test tell us?
Hereโs what I think it tells me:
- There is a
DayPercentileCalculator - It has a
calculatemethod - 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:
1 2 | assertThat(StringWrangler.wrangle("hello world")) .isEqualTo("hElLo wOrLd"); |
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:
1 2 3 4 5 | @Testvoid dayPercentile() { assertThat(DayPercentileCalculator.calculate(new Time(12, 0, 0)) .isEqualTo("50%");} |
Ignore the made up Time type here.
We can understand with a minimum of guesswork how this code must surely operate.
Summary
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.
Published on Java Code Geeks with permission by Ashley Frieze, partner at our JCG program. See the original article here: What are we Testing Again? Opinions expressed by Java Code Geeks contributors are their own. |
Thank you!
We will contact you soon.
Ashley FriezeOctober 20th, 2019Last Updated: October 18th, 2019

This site uses Akismet to reduce spam. Learn how your comment data is processed.