Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我可以在第一个方法的then语句中模拟另一个方法吗?_Java_Scala_Mockito - Fatal编程技术网

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

Java 我可以在第一个方法的then语句中模拟另一个方法吗?,java,scala,mockito,Java,Scala,Mockito,我可以在中模拟另一个方法吗,然后是模拟方法的语句 我正在模拟ResultSet.getByte()中的两个不同参数 when(rs.getByte("present")).thenReturn(5) when(rs.getByte("missing")).thenReturn(0) 我还想得到的是,mockgetByte不仅返回值,还返回mockResultSet.wasNull,在第一种情况下返回一次false,在另一种情况下返回一次true 下面是我如何运行该场景 val rs: Wrap

我可以在
中模拟另一个方法吗,然后是模拟方法的
语句

我正在模拟
ResultSet.getByte()
中的两个不同参数

when(rs.getByte("present")).thenReturn(5)
when(rs.getByte("missing")).thenReturn(0)
我还想得到的是,mock
getByte
不仅返回值,还返回mock
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
getter内部调用
wasNull
,紧跟在
getByte

之后,会出现什么问题:

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

也许可以这样做:

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;
   }
}
final ResultSet rs=mock(ResultSet.class);
当(rs.getByte(anyString())。然后回答(new Answer()){
@凌驾
公共长回答(invocationMock invocationMock)抛出可丢弃的{
字符串参数=(字符串)invocationOnMock.getArguments()[0];
长话短说;
如果(“当前”。等于(参数)){
when(rs.wasNull()).thenReturn(false);//mock返回false,when present是参数
答案=5L;
否则{
when(rs.wasNull()).thenReturn(true);//mock在向方法发送其他内容时返回true
答案=0升;
}
返回答案;
}
}

问题已更新。我有20个类似于
byteOpt
的getter。每个getter我必须对这些方法进行两次模拟。我想避免这种情况,那么您的问题的性质就不同了:您的生产代码对许多事情都有影响。如果您需要这么多模拟,我建议您后退一步;或者自己重新设计;或者请不要在您的问题中提供更多信息。谢谢!我的问题不是我必须支持两个参数。我不知道在执行第一个mock之前是否可以有条件地模拟其他方法:)嗯,好的:P对不起。我想你想在执行后模拟它,这就是为什么在if块中模拟内部回答的原因。在你的行之后:“我还想得到的是,模拟的getByte不仅返回值,而且还返回mock ResultSet.wasNull,在第一种情况下返回一次false,在另一种情况下返回一次true。”