wtorek, 8 stycznia 2013

More granural exceptions testing with JUnit 4 and ExpectedException

It took me quite long time to finally get myself together and write my first post. To be honest, I was inspired by a friend I work together on a project who started blogging some time ago. You can find his blog here

I decided to blog on something simple yet useful first, before I start a series of articles related to JAXB

When I moved from JUnit 3 to JUnit 4 it hit me how elegant it is to verify whether exceptions get thrown from your code. The expected argument of @Test annotation is just so nice, but it allows you only to test whether an exception of desired class has been thrown. But what if you require more granual control?

ExpectedException to the rescue!!!.

On the Expected exception you can setup simple expectations (like when using mocks) and JUnit framework will verify them automatically

    private static final String EXCEPTION_MESSAGE = "Test exception message";

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void testNullPointerExceptionSimpleMessageCheck() {
        thrown.expect(NullPointerException.class);
        thrown.expectMessage(EXCEPTION_MESSAGE);

        throw new NullPointerException(EXCEPTION_MESSAGE);
    }

What is really cool, is that you can pass Hamcrest matcher to the expect method, which gives you absolute control on how you would like to verify, whether proper exception has been thrown

    @Test
    public void testExceptionWithHamcrestMatcher() {
        thrown.expect(isNullPointerWithTestExceptionMessage());

        throw new NullPointerException(EXCEPTION_MESSAGE);
    }

    private static Matcher<Throwable> isNullPointerWithTestExceptionMessage() {
        return new BaseMatcher<Throwable>() {
            @Override
            public boolean matches(Object o) {
                if (o instanceof NullPointerException) {
                    NullPointerException npe = (NullPointerException) o;
                    return EXCEPTION_MESSAGE.equals(npe.getMessage());
                }
                return false;
            }

            @Override
            public void describeTo(Description description) {
            }
        };
    }

You can find full sourcecode on my git repository

Just a small update. A friend of mine, sent me this link about catch-exception library. The definite advantage of this solution is that, apart from verifying whether appropriate exception has been thrown, you can add, say, verification of some of your mocks. You can for instance verify, that because of an exception being thrown, no other method in the flow has been called.

1 komentarz:

  1. Congrats on your blog :) This is a very interesting entry. Keep up with the good work :D

    OdpowiedzUsuń