Nifty JUnit : How to test for an exception
Testing for exceptions in JUnit is something we have to deal with! We want to test if an exception occurs in a particular situation, or even if the exception contains a particular message. The question is: How to test for an exception in Junit? What we see very often is this:
import org.junit.Test;
public class JDrivenServiceTest {
JDrivenService service = new JDrivenService();
@Test(expected = ArticleNotFoundException.class)
public void testPublishArticle_WithException() throws Exception {
service.publishArticle(null);
}
}
Or this, which is worse in my opinion:
import org.junit.Test;
import static org.junit.Assert.fail;
public class JDrivenServiceTest {
JDrivenService service = new JDrivenService();
@Test
public void testPublishArticle_WithException() throws Exception {
try {
service.publishArticle(null);
fail();
} catch (ArticleNotFoundException e) {
//Do some Asserts here.
}
}
}
What would be much better is to use the @Rule Annotation in combination with the ExpectedException class like this:
import org.junit.Test;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
public class JDrivenServiceTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
JDrivenService service = new JDrivenService();
@Test
public void testPublishArticle_WithException() throws Exception {
thrown.expect(ArticleNotFoundException.class);
thrown.expectMessage("Article not found");
thrown.expectMessage("please provide an article to publish");
service.publishArticle(null);
}
}