2012-08-29 328 views

回答

0

你可以嘗試捕捉所需的異常,這樣做assertTrue(true)

@Test 
testIfThrowsException(){ 
    try{ 
     funcThatShouldThrowException(arg1, agr2, agr3); 
     assertTrue("Exception wasn't thrown", false); 
    } 
    catch(DesiredException de){ 
     assertTrue(true); 
    } 
} 
+0

你是什麼意思?你能詳細說明嗎? – RNJ

+0

添加代碼示例 – assafmo

+1

如果沿着此路徑走下去,請使用「失敗」,並且不要在catch語句中包含任何內容。 –

12

在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?"); 
     } 
} 
+0

我以前沒有看到過。感謝分享。這與@Test(期望...)相比有什麼優勢嗎?今晚晚些時候我得看看這個 – RNJ

+1

@RNJ,幾天前我第一次看到它。但它工作順利,就像人們期望的那樣。 – dantuch

+0

這是我的晚上排序然後;) – RNJ

5

我知道的兩個選項。

如果使用junit4

@Test(expected = Exception.class) 

,或者使用junit3

try { 
    methodThatThrows(); 
    fail("this method should throw excpetion Exception"); 
catch (Exception expect){} 

的這兩個捕獲異常。我會建議捕捉你正在尋找的異常,而不是通用的異常。

+0

+1爲JUnit 4方法。這是迄今爲止我見過的最常見的,很好的自我記錄。 –

相關問題