问题
If a method throwing an exception, how to write a test case to verify that method is actually throwing the expected exception?
回答1:
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:
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?");
}
}
回答3:
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.
来源:https://stackoverflow.com/questions/12184281/how-to-handle-exceptions-while-unit-testing-using-junit