Software Development

What are we Testing Again?

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
@Test
void 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 calculate method
  • 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
@Test
void 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.

Ashley Frieze

Software developer, stand-up comedian, musician, writer, jolly big cheer-monkey, skeptical thinker, Doctor Who fan, lover of fine sounds
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button