2016-08-15 61 views
1

如何測試一個方法什麼都不做。例如,我有一個靜態方法,如果給定的字符串參數爲null或空(它用於參數驗證),則會引發異常。現在我的測試是這樣的:JUnit4 - 測試方法什麼都不做

@Test 
public void notNullOrEmpty_doesNothingIfValueIsNotNullOrEmpty() { 
    Require.notNullOrEmpty(Generate.randomString()); 
    assertTrue(true); // <- this looks very ugly 
} 

@Test(expected = IllegalArgumentException.class) 
public void notNullOrEmpty_throwsExceptionIfValueIsNull() { 
    Require.notNullOrEmpty(null); 
} 

@Test(expected = IllegalArgumentException.class) 
public void notNullOrEmpty_throwsExceptionIfValueIsEmpty() { 
    Require.notNullOrEmpty(""); 
} 

我怎樣才能讓第一個測試通過,而無需調用assertTrue(true),有Assert.fail()是有什麼樣的Assert.pass()

編輯: 新增失蹤(expected = IllegalArgumentException.class)至3測試

+0

萬一需要類不真的只是檢查null或空考慮使用從番石榴庫Preconditions.checkArgument(Strings.isNullOrEmpty(「MyString的」))井試驗班; – sandrozbinden

+0

同時請記住仔細使用隨機生成的字符串作爲測試輸入。請參閱http://stackoverflow.com/questions/3441686/what-are-the-downsides-using-random-values-in-unit-testing – sandrozbinden

回答

5

您只需在第一種方法中刪除斷言。

@Test 
public void notNullOrEmpty_doesNothingIfValueIsNotNullOrEmpty() { 
    Require.notNullOrEmpty(Generate.randomString()); 
    // Test has passed 
} 

如果測試方法完全運行,則表示它傳遞成功。看看Eclipse中的JUnit輸出:

enter image description here

更新:作爲一個額外的評論,如果你使用框架的Mockito你可以利用verify方法來驗證的方法被稱爲X倍。舉例來說,我使用的是這樣的:

verify(cmAlertDao, times(5)).save(any(CMAlert.class)); 

在你的情況,因爲你正在測試靜態方法,那麼你可能會發現有用使用PowerMock它可以驗證靜態方法(因爲做的Mockito沒有)。你可以使用verifyStatic(...)

+0

所以,只是不主張任何事情會使測試通過? – danielspaniol

+0

@Exhauzt是的,正確的。我已添加了答案的更新。但是,您可以使用Mockito框架和'verify'來確定一個方法被稱爲X數量。你也可以使用PowerMock來驗證被調用的靜態方法。 –

+0

@Exhauzt,只是要清楚,如果你只使用JUnit,那麼沒有聲明任何東西都會使測試通過。 –

3

您應該添加註釋@Test(expected = YourException.class)

嘗試添加到第一個測試:

@Test 
public void notNullOrEmpty_doesNothingIfValueIsNotNullOrEmpty() { 
    String str = Generate.randomString(); 
    Require.notNullOrEmpty(str); 
    assertNotNull(str); 
} 

,並可能對你有更好的,因爲你不爲空值測試它重命名爲notNullOrEmpty_doesNothingIfValueIsNotNullOrNotEmpty

+0

我有這個...測試它應該拋出一個異常。但是我想讓第一個測試更清晰 – danielspaniol

0

單元測試必須聲明預期的方法行爲。
如果在你的規範中,當你的調用notNullOrEmpty()當數據有效時必須拋出異常,並且當數據無效時必須拋出異常,所以在你的單元測試中你必須在數據有效時不做斷言,因爲if它不會成功,將拋出異常並且測試將會失敗。

@Test 
public void notNullOrEmpty_doesNothingIfValueIsNotNullOrEmpty() { 
    Require.notNullOrEmpty(Generate.randomString()); 
}