[英]How to handle exceptions while unit testing using JUnit?
如果一個方法拋出異常,如何編寫一個測試用例來驗證該方法實際上是否拋出了預期的異常?
在最新版本的JUnit中,它以這種方式工作:
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);
}
}
更多關於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?");
}
}
我知道的兩個選項。
如果使用junit4
@Test(expected = Exception.class)
或者如果使用junit3
try {
methodThatThrows();
fail("this method should throw excpetion Exception");
catch (Exception expect){}
這兩個都捕獲異常。 我建議捕獲您正在尋找的異常而不是通用異常。
您可以嘗試捕獲所需的異常並執行類似assertTrue(true)
:
@Test
testIfThrowsException(){
try{
funcThatShouldThrowException(arg1, agr2, agr3);
assertTrue("Exception wasn't thrown", false);
}
catch(DesiredException de){
assertTrue(true);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.