Java Mock抛出异常,然后返回值?

Wig*_*ige 6 java unit-testing mockito

我正在使用JUnit 4和Mockito2。我试图模拟一种情况,其中模拟函数在首次调用时会返回异常,然后在后续调用中返回有效值。我试着简单地让其thenThrow()后跟一个thenReturn(),但这显然不是正确的方法

when(stmt.executeUpdate()).thenThrow(new SQLException("I have failed."));
when(stmt.executeUpdate()).thenReturn(1);
sut.updateValue("1");
verify(dbc).rollback();
sut.updateValue("2");
verify(dbc).commit();
Run Code Online (Sandbox Code Playgroud)

但是,这两个调用都导致对catch语句中的rollback()的调用。

Tim*_*kle 11

最简单的方法是这样的:

when(stmt.executeUpdate())
     .thenThrow(new SQLException("I have failed."))
     .thenReturn(1);
Run Code Online (Sandbox Code Playgroud)

但是单元测试中的单一方法应该验证对代码行为的单一期望。因此更好的方法是编写两个单独的测试方法。

  • 如果有人想知道,您可能想要这样的原因是您正在测试的方法是否多次调用模拟方法。那么你需要这样的东西来控制执行。 (2认同)

小智 6

thenAnswer()与Answer具有某种状态的自定义一起使用,例如:

class CustomAnswer extends Answer<Integer> {

    private boolean first = true;

    @Override
    public Integer answer(InvocationOnMock invocation) {
        if (first) {
            first = false;
            throw new SQLException("I have failed.");
        }
        return 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

一些阅读:https : //akcasoy.wordpress.com/2015/04/09/the-power-of-thenanswer/(注意:不是我的博客)