2017-08-09 190 views
3

我正在使用JUnit 4和Mockito 2.我试图模拟mocked函数在第一次调用时返回异常并在随后的调用中返回有效值的情况。我想简单地有thenThrow()后跟一个thenReturn(),但这不是正确的方法显然Java Mock抛出一个异常,然后返回一个值?

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(); 

两种电话,然而,导致通话回滚(),这是在catch语句。

回答

3

使用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; 
    } 
} 

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

+0

真棒,这工作完美,谢谢! – Wige

1

你也可以创建两个单独的测试。 要验证你可以做类似的异常:

@Test(expected = SQLException.class) 
public void yourTest()throws Exception{ 
stmt.executeUpdate(); //set your logic to produce the exception 
} 

然后再拍测试成功场景

0

最简单的方法是这样的:

when(stmt.executeUpdate()) 
    .thenThrow(new SQLException("I have failed.")) 
    .thenReturn(1); 

但是,在一个单位一个单一的方法测试应该验证一个单一期望关于代码行为。因此更好的方法是写两个独立的测试方法。

相关问题