Platinum Partner
java,testing

Unexpected Behavior in JUnit’s ExpectedException

In a previous post, I described my preference of the relative new ExpectedException rule over the more traditional strategies for verifying expected exceptions: the good-old “try-fail-catch” pattern and the “expected” attribute in JUnit’s @Test annotation. I thought, and I still think, that this new tool provides the best features of its predecessors: code brevity and the ability to specify which line of code is the one we expect to throw an exception. The only point I missed: it is not foolproof.

In a previous conversation with my good friend and colleague Stuart, we agreed that we need to be careful enough to place the check for an expected exception just before the line of code that is supposed to throw such exception, in order to verify that the exception is thrown at the correct time. The following example is taken from FEST’s Assertions:

// Note: I'm using the ExpectedException rule I created myself in the previous post.
@Rule public ExpectedException thrown = none();

private StringAssert assertions;

@Before public void setUp() {
assertions = new StringAssert("Leia");
}

@Test public void should_fail_if_actual_is_not_equal_to_expected() {
thrown.expectAssertionError("expected:<'Yoda'> but was:<'Leia'>");
assertions.isEqualTo("Yoda");
}

So far, so good. A couple of nights ago, I discovered by accident that any code placed after the line that throws the exception will never get executed if the expected exception is actually thrown. For example, in the following code listing, I was checking that the mocks were correctly called after the expected exception is thrown (BTW, I’m using Mockito.)

@Rule public ExpectedException thrown = none();

private StringAssert assertions;
private Failures failures;

@Before public void setUp() {
assertions = new StringAssert("Leia");
failures = spy(Failures.instance());
assertions.failures = failures;
}

@Test public void should_fail_if_actual_is_not_equal_to_expected() {
thrown.expectAssertionError("expected:<'Yoda'> but was:<'Leia'>");
assertions.isEqualTo("Yoda");
verify(failures).fail(assertions.info, isNotEqual(assertions.actual, "Yoda"));
}

The problem here is that line 15 will never be executed if line 14 throws the expected exception! This test will always pass as long as the expected exception is thrown, even if I remove the calls to Failures from StringAssert.

The reason behind this behavior is actually quite simple. By looking at the source of ExpectedException, we can tell immediately that once the expected exception is caught, it is impossible to continue the execution of the test method:

@Override public void evaluate() throws Throwable {
try {
fNext.evaluate();
} catch (Throwable e) {
if (fMatcher == null) throw e;
Assert.assertThat(e, fMatcher);
return;
}
if (fMatcher != null)
throw new AssertionError("Expected test to throw "
+ StringDescription.toString(fMatcher));
}

I fixed this test by replacing the ExpectedException rule with the traditional “try-fail-catch” pattern:

@Test public void should_fail_if_actual_is_not_equal_to_expected() {
try {
assertions.isEqualTo("Yoda");
fail();
} catch (AssertionError e) {
assertEquals("expected:<'Yoda'> but was:<'Leia'>", e.getMessage());
}
verify(failures).fail(assertions.info, isNotEqual(assertions.actual, "Yoda"));
}

Not surprisingly, it turns out that Stuart had a similar thought about the subject. After a brief chat, we came up with the following patterns for using ExpectedException effectively:

  1. the check for the expected exception must be immediately above the code that is expected to throw such exception
  2. the line of code that is expected to throw an exception should be the last line in the test method

From http://alexruiz.developerblogs.com/?p=1678

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}