我可以在第一种方法的声明中模拟另一种方法吗?

时间:2016-08-19 10:01:53

标签: java scala mockito

我可以在模拟方法的then语句中模拟另一种方法吗?

我正在嘲笑ResultSet.getByte() 2个不同的论点

when(rs.getByte("present")).thenReturn(5)
when(rs.getByte("missing")).thenReturn(0)

我还想要的是,模拟getByte不仅会返回值,还会模拟ResultSet.wasNull,在第一种情况下返回false,在另一种情况下返回true

以下是我如何运行方案

val rs: WrappedResultSet = ...
val res3: Option[Byte] = rs.byteOpt("present")
val res4: Option[Byte] = rs.byteOpt("missing")
res3.isDefined should be(true)
res4.isDefined should be(false)

byteOpt之后,wasNull getter内部调用getByte的实施。

2 个答案:

答案 0 :(得分:2)

也许做那样的事情:

final ResultSet rs = mock(ResultSet.class);
when(rs.getByte(anyString())).thenAnswer(new Answer<Long>() {
   @Override
   public Long answer(InvocationOnMock invocationOnMock) throws Throwable {
       String argument = (String) invocationOnMock.getArguments()[0];
       Long answer;
       if("present".equals(argument)){
          when(rs.wasNull()).thenReturn(false); //mock to return false, when present was argument
          answer = 5L;
       else {
          when(rs.wasNull()).thenReturn(true); //mock to return true, when something else was sent to method
          answer = 0L;
       }
       return answer;
   }
}

答案 1 :(得分:0)

会出现什么问题:

when(rs.getByte("present")).thenReturn(5);
when(rs.wasNull()).thenReturn(false);