即使在其中一个依赖项调用抛出异常之后也验证调用的测试用例

Test case to verify invocation even after one of the dependency call throws exception

在我的方法中,我调用了两个依赖项 depA.foo() 和 depB.bar()。如果 depA 抛出异常,那么我不希望调用 depB。 (反之亦然)。所以在代码库中,对 depA 的调用应该在对 B 的调用之前。

有没有一种方法可以编写测试用例来测试 depB() 的调用,而无需显式捕获调用 A 抛出的异常?

我可以通过将 verify() 放在 finally 块中来做到这一点,但不确定这是否是正确的方法。如果有任何其他标准方法可以做到这一点,请告诉我

//Sample code
public void someMethod(){
depA.foo();
depB.bar();
}
//Sample Test
@Test(expectedExceptions = {RuntimeException.class})
public void someTest(){
when(depA.foo()).thenThrow(new RuntimeException("Some method"));
try{
 toTestClass.someMethod();
} finally {
 verify(depB,times(0)).bar();
}
}

大多数时候,我使用类似的东西:

@Test
public void someTest(){
    when(depA.foo()).thenThrow(new RuntimeException("Some method"));
    boolean hasException = false;
    try{
        toTestClass.someMethod();
    } catch(RuntimeException e) {
        hasException = true;
    }
    assertTrue(hasException);
    verify(depB,times(0)).bar();
}

为什么?

  1. 我认为 expectedExceptions 应该只在你需要的时候使用 检查异常。不是断言的混合体。
  2. 你不想verify如果异常 没有追加。

编辑: 您也可以使用像 AssertJ 这样的第三方断言库。 AssertJ 可以很好地处理异常。 请参阅其文档:https://joel-costigliola.github.io/assertj/assertj-core-features-highlight.html#exception-assertion

@Test
public void someTest(){
     when(depA.foo()).thenThrow(new RuntimeException("Some method"));
     assertThatThrownBy(() -> { toTestClass.someMethod() })
                        .isInstanceOf(RuntimeException.class)
                        .hasMessageContaining("Some method");
     verify(depB,times(0)).bar();
}

您可以使用 Fisbowl 库的 ignoreException

@Test
public void someTest(){
   when(depA.foo()).thenThrow(new RuntimeException("Some method"));
   ignoreException(() -> toTestClass.someMethod());
   verify(depB,times(0)).bar();
}