dan*_*iol 2 java testing junit junit4
如何测试方法是否无效.例如,我有一个静态方法,如果给定的字符串参数为null或为空(它用于参数验证),则抛出异常.现在我的测试看起来像这样:
@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("");
}
Run Code Online (Sandbox Code Playgroud)
如何在没有通话的情况下让第一个测试通过assertTrue(true)
,有一个Assert.fail()
类似的东西Assert.pass()
?
编辑:添加缺少(expected = IllegalArgumentException.class)
第3测试
您只需要在第一种方法中删除断言.
@Test
public void notNullOrEmpty_doesNothingIfValueIsNotNullOrEmpty() {
Require.notNullOrEmpty(Generate.randomString());
// Test has passed
}
Run Code Online (Sandbox Code Playgroud)
如果测试方法完全运行,则意味着它成功通过.看看Eclipse junit输出:
更新:作为附加注释,如果您使用Mockito框架,您可以利用verify
方法来验证方法是否被调用了X次.例如,我使用了这样的东西:
verify(cmAlertDao, times(5)).save(any(CMAlert.class));
Run Code Online (Sandbox Code Playgroud)
在您的情况下,由于您正在测试静态方法,因此您可能会发现使用PowerMock有用,它允许您验证静态方法(因为Mockito没有).你可以使用verifyStatic(...)
.
归档时间: |
|
查看次数: |
2238 次 |
最近记录: |