Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpectedException in jUnit?

Is there an equivalent to NUnit's ExpectedException or Assert.Throws<> in jUnit?

like image 538
ripper234 Avatar asked Jun 27 '09 11:06

ripper234


People also ask

What is expected exception 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.

Does expectedexception have to be null?

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.

When to specify the type of the expected exception?

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:

What is the expected parameter in exception testing in Java?

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.


1 Answers

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.

like image 192
Maciej Biłas Avatar answered Nov 24 '22 22:11

Maciej Biłas