首页 > 解决方案 > Can unit/integration tests have no assert? And what about this particular case?

问题描述

Scenario: I have some integration tests. One of them tests a delete. So I've done:

@Test
@Order(6)
public void delete() {
    rfxCriteriRepository.delete(rfxCriteriEconomico.getIdrfxcriteri());
}

to simply test if the method throws no exception. Than, to be sure that the delete is successfull, I've added:

@Test
@Order(7)
public void getDelete() {
    RfxCriteri rfxCriteriEconomicoDb = rfxCriteriRepository.findByIdrfxcriteri(
        rfxCriteriEconomico.getIdrfxcriteri()
    );

    Assertions.assertNull(rfxCriteriEconomicoDb);
}

My idea is that the first test tests the code. If the code is well written, it should throw no exception, and the test pass. The second test tests that the delete effectively deleted the entry from the database. IMHO they are two separate tests.

Do you think every test must have an assert? Or do you think these two tests should be an unique test? Can someone point me to some guide about unit testing that says something about it?

标签: unit-testingtestingintegration-testingassert

解决方案


每个测试都要求以某种形式评估结果。但是,在某些情况下,这可能是隐含的。例如,许多测试框架将测试执行期间发生的未捕获和意外异常视为测试失败。当您使用这样的框架并且您有一个测试,其中重要的是没有引发异常,那么您可以编写该测试而无需任何明确的断言语句 - 框架为您执行断言。

然而,唯一成功标准是没有引发异常的测试并不常见。但是,在某些情况下这是有意义的:以经典的例子为例,三角形是通过传递长度和a三个边来定义的。然后,一个极端情况是两条边之和等于第三条边,如。然后,您可以使用三个测试用例来测试边界:bca == b + c

  1. 一种情况,其中两条边长的总和刚好高于(一个ε)第三条边的长度:a + epsilon == b + c- 在任何情况下这都是一个有效的三角形。
  2. 一种情况,其中一侧的长度(又是一个 epsilon)比其他两个的总和长,例如a - epsilon == b + c。这应该引发异常,因为这不是有效的三角形。
  3. 最后的情况在哪里a == b + c

假设在您的代码中,案例 3 的情况将产生一个退化但有效的三角形。然后有一个测试用例只是创建这个三角形 - 看看没有抛出异常是有意义的。请记住,您的测试也可以被视为代码的文档:这样的测试很好地记录了您的代码允许创建这样的三角形。在这种情况下,测试用例当然应该被实现和命名,以便意图变得清晰,例如“constructing_aDegenerateTriangle_shallSucceedWithoutExceptionRaised”。

现在,进入问题的第二部分,在您的特定情况下,没有断言的测试是否有意义。在这种情况下,我也只会认为 JBNizet 提到的组合测试是有用的(它会删除然后检查条目是否被真正删除)。您可以单独进行这两个测试 - 但对断言的一个测试将是多余的,因为测试框架的隐式断言检查无论如何都会在两个测试用例中完成。


推荐阅读