Over a million developers have joined DZone.

JUnit: Custom ExpectedException Rules…Rule!

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

I’ve been using JUnit 4.7′s ExpectedException rule for some time now and I love it! IMHO, it combines the best of the old JUnit 3.x pattern for verifying expected exceptions and the expected attribute of JUnit 4′s @Test annotation, without their downsides. Although this is nothing new, I’ll explain them briefly:

The old JUnit 3.x pattern for verifying expected exceptions looks like this:

public void shouldThrowNpeIfArgumentIsNull() {
  try {
    fail("Expecting NullPointerException");
  } catch (NullPointerException expected) {
    assertEquals("The text to encode should not be null", expected.getMessage());

The good thing about this pattern is that we can verify exactly where the exception we are expecting should be thrown. The downside is that is verbose and error-prone. It is easy to forget to call fail (line 6,) resulting in a test that never fails, even if the expected exception is never thrown!

JUnit 4 introduced the attribute expected in its @Test annotation, where we can specify the type of exception should be thrown by the code to test:

@Test(expected = NullPointerException.class)
public void shouldThrowNpeIfArgumentIsNull() {

IMHO, it made things worse. It definitely results in cleaner code, but the price to pay is that now we can’t check if the message of the expected exception is correct and we can’t specify the line of code that is supposed to throw an exception. If an NPE is thrown, which line actually did it?

Enter ExpectedException rule

JUnit 4.7 introduced rules, which are another extension mechanism for JUnit (you can read more about rules here.) Among those rules, my favorite is ExpectedException, because it allows us, with only a couple of lines of code, to verify both the type and the message of an expected exception *and* specify where the exception should be thrown (well, more or less.)

public class EncoderTest {
  @Rule public ExpectedException thrown = ExpectedException.none();
  public void shouldThrowNpeIfArgumentIsNull() {
    thrown.expectMessage("The text to encode should not be null");

The sour smell of code duplication

So far so good. Something I noticed is that in my code I was checking for the same type of exceptions over and over, resulting in code duplication. For example, I had this code in too many places:


Yeah, I know, this is only one line of code, but duplication really bothers me. I wished I could write the following:

thrown.expectAssertionError("[Test] expecting:<'Leia'> but got <'Yoda'>");

Actually, it is possible. We just have to write our own ExpectedException rule. Subclassing org.junit.rules.ExpectedException is not possible, since its constructor is private. Copy/pasting ExpectedException‘s code is a terrible idea. There is a better way.

The solution

I implemented my own ExpectedException by simply wrapping the JUnit one, protecting myself from future changes in ExpectedException‘s implementation:

public class ExpectedException implements MethodRule {
  private final org.junit.rules.ExpectedException delegate = org.junit.rules.ExpectedException.none();
  public static ExpectedException none() {
    return new ExpectedException();
  private ExpectedException() {}
  public Statement apply(Statement base, FrameworkMethod method, Object target) {
    return delegate.apply(base, method, target);
  public void expectAssertionError(String message) {
  public void expectNullPointerException(String message) {
  public void expect(Throwable error) {
  public void expect(Class<? extends Throwable> type) {
  public void expectMessage(String message) {


The (relatively) new ExpectedException rule is a nice addition to JUnit. It brings the benefits of the previous approaches for verifying expected exceptions, without their downsides. As useful as it is, ExpectedException can also introduce code duplication if we are verifying the same type of exception many times in our test suite. As a workaround, creating our own ExpectedException that already knows about the type of exceptions we expect in our test suite can reduce code duplication and make test code a little more readable. Writing one is easy, we just need to implement the interface org.junit.rules.MethodRule and delegate the actual behavior to a org.junit.rules.ExpectedException, something that takes seconds to do in modern IDEs.

Feedback is always welcome :)


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

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.


The best of DZone straight to your inbox.

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.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}