Software Development

The First and Last Rites

Let’s look at another test smell.

Consider the following tests:

@Test
public void connectionWorks() {
    database = openDatabase();

    database.healthCheck();

    database.close();
}

@Test
public void countRows() {
    database = openDatabase();

    assertThat(database.countAll())
      .isEqualTo(0);

    database.close();
}

In the above code we’ve written two tests for some fictional database. It looks like both those tests start and end with the same code. On top of that, it even looks like the database reference we’re using has been made an instance member of the test class. In this case, it looks like a clue that this test class is generally about that object.

The presence of repeated test setup and teardown across a couple of tests MAY be the sign of a missing before/after pattern. It may also be a coincidence.

On the whole, if all your tests need to go through the same ritual to get set up, you DO have a missing before. Similarly, if your instincts are telling you that the thing being created belongs as an instance member of the test class, then that thing probably gets set up in the before.

The example should be rewritten thus:

@Before
public void before() {
    database = openDatabase();
}

@After
public void after() {
    database.close();
}

@Test
public void connectionWorks() {
    database.healthCheck();
}

@Test
public void countRows() {
    assertThat(database.countAll())
      .isEqualTo(0);
}

As well as reducing the boilerplate, this also documents what’s going on for the authors of future test cases.

What if Not All Tests Do It The Same?

You can fall into the repeated first and last rites pattern when you mix different ways of constructing the system under test, or test data in the same test class.

You should consider each class a test fixture – i.e. the way of composing a certain group of similar tests. If there are some exceptions put them in a different class with its own modus operandi.

Published on Java Code Geeks with permission by Ashley Frieze, partner at our JCG program. See the original article here: The First and Last Rites

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