JUnit4 - 测试方法是否不执行任何操作

JUnit4 - Test if method does nothing

如果一个方法什么都不做,我该如何测试。例如,我有一个静态方法,如果给定的字符串参数为 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("");
}

如何在不调用 assertTrue(true) 的情况下使第一个测试通过,有一个 Assert.fail() 是否有类似 Assert.pass() 的东西?

编辑: 将缺失的 (expected = IllegalArgumentException.class) 添加到第三个测试

您应该添加 @Test(expected = YourException.class) 注释。

尝试添加到第一个测试:

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

可能您最好将其重命名为 notNullOrEmpty_doesNothingIfValueIsNotNullOrNotEmpty,因为您正在测试它的非空值。

您只需删除第一种方法中的断言。

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

如果测试方法完全运行,则表示成功通过。查看 Eclipse junit 输出:

更新:作为附加评论,如果您使用 Mockito 框架,您可以利用 verify 方法来验证某个方法被调用了 X 次。例如,我使用了这样的东西:

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

在您的情况下,由于您正在测试静态方法,因此您可能会发现使用 PowerMock 很有用,它允许您验证静态方法(因为 Mockito 没有)。你可以使用 verifyStatic(...).

单元测试必须断言方法行为中的预期行为。
如果在您的规范中,当您的调用 notNullOrEmpty() 数据有效时不得抛出异常,而数据无效时必须抛出异常,那么在您的单元测试中,当数据有效时您不得断言因为如果它不成功,将抛出异常并且测试将失败。

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