Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Unexpected Behavior in JUnit’s ExpectedException

DZone's Guide to

Unexpected Behavior in JUnit’s ExpectedException

· Java Zone
Free Resource

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

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

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}