| Testing Exceptions in JUnit 4.7 |
|
|
JUnit 4.7 introduced a few features that make it a little easier to work with exceptions. JUnit 4 introduced the expected parameter, which makes a test succeed if and only if a certain exception is thrown. For example, in the following code sample, we are testing a UserManager class. When the Our UserDao class will return
This approach is useful for simple cases, but it has its limits. For example, you can't test the value of the message in the exception, or the state of a domain object after the exception has been thrown. In JUnit 4.7, however, you can now use the
The This is great if all you need to do is test the exception thrown and the associated message. However if you need to check the state of the domain objects that are manipulated during the tests, you start to run into the limits of JUnit 4.7's new features. One option would be to use the Verifier rule, which lets you check the state of your objects after each test and force the test to fail under certain circumstances, as shown here:
However, since this method will be called after every test, it would not scale well - indeed, this is probably not really the intended use of Verifier rules, which should ideally be state checks that would be applicable for all of the tests in your class. So, before you get too wrapped up in complicated solutions, you might simply want to fall back on the old try-catch-fail strategy in these cases. Trackback(0)
Comments (2)
![]() written by Adrian, September 30, 2009
@Andy any line after the call to #expect! Thus if you move these lines further down your test, you can exclude the "setup" from throwing expected exception.
Write comment
|
|
With expected type syntax, any line could throw the exception and the test would pass :-(