Is there an equivalent to NUnit's ExpectedException or Assert.Throws<> in jUnit?
JUnit adds expected exceptions. JUnit responded back to the users need for exception handling by adding a @Test annotation field "expected". The intention is that the entire test case will pass if the type of exception thrown matched the exception class present in the annotation.
Also, this test does not actually require the exception message to not be null, as long as the right type of exception is thrown. This passes the test: If we want to test anything beyond that the exception type, we’re going to need a @Rule annotation and the ExpectedException class.
After specifiying the type of the expected exception your test is successful when such an exception is thrown and it fails if a different or no exception is thrown. Instead of specifying the exception's type you can characterize the expected exception based on other criterias, too:
By using “expected” parameter, you can specify the exception name our test may throw. In above example, you are using “ IllegalArgumentException” which will be thrown by the test if a developer uses an argument which is not permitted. Let’s understand exception testing by creating a Java class with a method throwing an exception.
You might also consider taking a look at the ExpectedException class which provides richer exception matching.
https://github.com/junit-team/junit/wiki/Exception-testing
Not only you can match the exception class but also you can apply custom matchers to its message.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With