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:

What would be much better is to use the @Rule Annotation in combination with the ExpectedException class like this:


This entry was posted in Coding, Java, TDD by Willem Cheizoo. Bookmark the permalink.

About Willem Cheizoo

I'm Willem Cheizoo, since 2012 I work as a Java Software Developer at JDriven. I am constantly searching for more effective ways of implementing and building good quality software. By writing blogposts I am sharing my knowledge and experience with you.

One thought on “Nifty JUnit : How to test for an exception

  1. Pingback: How to test for an exception with Spock | JDriven BlogJDriven Blog

Leave a Reply

Your email address will not be published. Required fields are marked *