Core Java

Checking What’s Thrown in Java Tests

Someone came up with the idea of using try and catch blocks in unit tests in Java:

1
2
3
4
5
6
7
8
@Test
public void test() {
   try {
      callSomeCode();
   } catch (Exception e) {
      assertEquals("foo", e.getMessage());
   }
}

The above is tempting, but doesn’t work. If the code under test didn’t throw, then no assertion would be performed.

So to fix it:

01
02
03
04
05
06
07
08
09
10
11
@Test
public void test() {
   try {
      callSomeCode();
 
      // if we get here there was no exception
      fail();
   } catch (Exception e) {
      assertEquals("foo", e.getMessage());
   }
}

We add a fail which makes it a complete test that the right thing was thrown, but that’s awkward.

This is an example of an over exertion assertion from the test smells.

How Many Ways To Test What’s Thrown?

All the ways I know:

  • Do it the long way (above)
  • Use the @Test(expected = ... ) annotation to check for a test ending in the right sort of exception
  • Use the ExpectedException JUnit rule that allows you to define what you want your test to end with
  • Use an assertion that catches the exception for you

Why the expected exception pattern doesn’t work

The rule, explained against the long way round approach here allows you to define the success criteria of a test function that ends in an exception.

E.g.

01
02
03
04
05
06
07
08
09
10
11
12
// default to expecting no exception
@Rule
public ExpectedException expectedException = ExpectedException.none();
 
@Test
public void test() {
  // the call should end in the right exception
  expectedException.expectMessage(is("foo"));
 
  // do the call
  callSomeCode();
}

This is attractive, but still wrong

What Ever Happened to Given/When/Then?

Tests should read from top to bottom with assertions at the end. The expected exception pattern has to define the assertions/expectations before the call which produces them, which is backwards.

Conversely:

1
2
3
4
5
@Test
public void test() {
  assertThatThrownBy(() -> callSomeCode())
      .hasMessage("foo");
}

Is succinct and reads forwards.

Published on Java Code Geeks with permission by Ashley Frieze, partner at our JCG program. See the original article here: Checking What’s Thrown in Java Tests

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