Alex is a Software Engineer working on Android development tools, especially Android Studio, at Google. His interests include Java, API design, OOP, IDEs and testing. Alex spends some of his spare time working on Open Source, blogging, writing technical articles, and speaking at international conferences. The opinions expressed here represent his own and not those of his employer. Alex is a DZone MVB and is not an employee of DZone and has posted 49 posts at DZone. You can read more from them at their website. View Full User Profile

Unexpected Behavior in JUnit’s ExpectedException

10.29.2010
| 6395 views |
  • submit to reddit

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

Published at DZone with permission of Alex Ruiz, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Tomasz Nurkiewicz replied on Fri, 2010/10/29 - 2:05am

I had somewhat similar mixed feelings about ExpectedException rule, which does not fit into given/when/then test pattern. My idea was to catch and swallow the exception thrown from class under test and allow test case to continue. Verification happens afterwards. See my article here: Testing for exceptions in JUnit revised.

Thomas Mauch replied on Fri, 2010/10/29 - 6:35am

You may find my post Effectively Handling Exceptions in Testing Using MagicTest interesting which compares JUnit's ExpectedException with a new approach to unit test called MagicTest.

MagicTest features a visual approach which makes testing error cases as easy as sucessful ones.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.