JUnit ExpectedException Rule vs. Catch-Exception
During one of my conference talks I got an interesting question: "why do you prefer to test exceptions using catch-exception library instead of using ExpectedException Rule of JUnit?". This is a good question, so let me answer.
First of all, let us see both solutions.
You can read about
ExpectedException rule at https://github.com/junit-team/junit/wiki/Exception-testing.
To learn about
catch-exception go to http://code.google.com/p/catch-exception/.
Ok, so now we can answer the question.
You can learn more about testing from my book "Practical Unit Testing"
And by the way - the JUnit version is coming soon! :)
Not Only JUnit
The first reason is that some of the projects I work with use JUnit and some TestNG. Both frameworks offer different mechanisms for testing of the expected exception. Catch-exception lets me use the same idiom no matter which framework I use, which is very convenient.
What I like about catch-exception is that it does not break the arrange/act/assert or given/when/then flow of my tests.
This is unfortunately not possible with the ExpectedException rule, because you have to specify first what is expected, so the assertion part happens before the actual execution.
Stop the Test
In case of the ExpectedException rule the test stops after an exception is thrown. In some (rare) scenarios this is not welcomed, because sometimes you would like to verify some other stuff before claiming that the test passed.
In case of catch-exception the test goes on, and you can have additional assertions afterwards.
- It is better to use @Test(expected = ...) than to not test exceptions at all.
- It is better to use ExpectedException rule than @Test(expected = ...)
- It is better to use catch-exception than ExpectedException rule.
Keep on testing! :)