2012-04-22 51 views
0

我有一個方法:doctorQueue,它獲得三個參數:數據類型(由java.util.Date),時間和ID(字符串)。Java-Junit/Junit方法的誤解

返回值爲void,如果在同一時間已經有隊列,則給予豁免。

我寫了一個方法,使用JUnit:

public void checkQueueDoctor(){ 
Date date = new Date (2012,4,25); 
Time time = new Time (13, 0, 0); 
assertTrue(doctorQueue("83849829", date, time)); 
..... // and so on 
} 

它給我的下一個問題:The method assertTrue(boolean) in the type Assert is not applicable for the arguments (void)

我當然明白了,但是我怎麼可以檢查函數,它返回的值是無效的呢?

回答

1
public void checkQueueDoctor(){ 
    Date date = new Date (2012,4,25); 
    Time time = new Time (13, 0, 0); 
    doctorQueue("83849829", date, time); 
    ..... // and so on 
} 

就足夠了。如果拋出異常,測試將自動失敗。

0

確認在添加醫生後隊列已更改。

0

我該如何檢查函數,它返回的值是無效的?

你不行。你只能檢查它是否應該拋出一個例外,壞參數等,並通過Assert.fail()
被告知你可以做的是創造一個檢查這種方法的副作用的包裝方法和返回truefalse,如果你想測試調用來自斷言

1

如果有例外不是由一個void方法拋出,一個常見的模式是:

try { 
    doctorQueue("83849829", date, time); 
    // if we make it to this line, success! 
} catch (Exception e) { 
    fail("queue adding threw an exception"); 
} 

如果你有,你要檢查確實拋出異常的方法,只要將不能調用其他情況另一塊:

try { 
    doctorQueue(alreadyPresentElement, date, time); 
    fail("expected an exception but didn't get one!");  
} catch (Exception e) { 
    // we expected an exception and got it! Success! 
} 

(在這兩種情況下,它可能更好地搭上了更具體的異常不僅僅是Exception,順便說一句。)

+1

如果你想測試一個異常沒有被拋出一個方法,只是調用該方法。通過調用該方法嘗試... catch,你隱藏了原始異常 – NamshubWriter 2012-04-22 15:52:28

1

如果您正在使用JUnit 4,您可以檢查預期的異常,例如:

@Test(expected = Exception.class) 
public void checkQueueDoctor() throws Exception { 
    Date date = new Date (2012,4,25); 
    Time time = new Time (13, 0, 0); 
    doctorQueue("83849829", date, time); 
} 

你可以看一下這個link

+1

我認爲問題是如何測試是否拋出異常。我相信你的例子來測試一個異常對海報想要測試的其他場景很有用 – 2012-04-22 18:05:15