2016-08-15 62 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()); 
}