If a method throwing an exception, how to write a test case to verify that method is actually throwing the expected exception?
3 Answers
In newest versions of JUnit it works that way:
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class NumberFormatterExceptionsTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void shouldThrowExceptionWhenDecimalDigitsNumberIsBelowZero() {
thrown.expect(IllegalArgumentException.class); // you declare specific exception here
NumberFormatter.formatDoubleUsingStringBuilder(6.9, -1);
}
}
more on ExpectedExceptions:
http://kentbeck.github.com/junit/javadoc/4.10/org/junit/rules/ExpectedException.html
http://alexruiz.developerblogs.com/?p=1530
// These tests all pass.
public static class HasExpectedException {
@Rule
public ExpectedException thrown= ExpectedException.none();
@Test
public void throwsNothing() {
// no exception expected, none thrown: passes.
}
@Test
public void throwsNullPointerException() {
thrown.expect(NullPointerException.class);
throw new NullPointerException();
}
@Test
public void throwsNullPointerExceptionWithMessage() {
thrown.expect(NullPointerException.class);
thrown.expectMessage("happened?");
thrown.expectMessage(startsWith("What"));
throw new NullPointerException("What happened?");
}
}
4 Comments
RNJ
I havent seen this before. thanks for sharing. Does this have any advantage over doing @Test(expected...). I'll have to look this up later tonight
dantuch
@RNJ, I have seen it first time few days ago. But it works smoothly, just the way someone would expect.
RNJ
that's my evening sorted then ;)
Ratnakar.class
@Dantuch that is useful answer. Could you please put your valuable comments on gfgqtmakia answer, accepted for earlier versions of Junit.
Two options that I know of.
If using junit4
@Test(expected = Exception.class)
or if using junit3
try {
methodThatThrows();
fail("this method should throw excpetion Exception");
catch (Exception expect){}
Both of these catch Exception. I would recommend catching the exception you are looking for rather than a generic one.
1 Comment
Peter Bratton
+1 for the JUnit 4 approach. It's by far the most common I've seen, and quite well self-documenting.
You can try and catch the desired exception and do something like assertTrue(true):
@Test
testIfThrowsException(){
try{
funcThatShouldThrowException(arg1, agr2, agr3);
assertTrue("Exception wasn't thrown", false);
}
catch(DesiredException de){
assertTrue(true);
}
}
2 Comments
RNJ
What do you mean? Can you elaborate?
Michael Lloyd Lee mlk
If you go down this path use "fail" and don't include anything in the catch statement.