我试图在调用具有可变数量的参数(...Java中的东西)的方法时使用参数匹配器而没有成功.我的代码在下面,我还列出了我尝试使用的所有行来完成这项工作.
import static org.mockito.Mockito.*;
public class MethodTest {
public String tripleDot(String... args) {
String sum = "";
for (String i : args) {
sum += i;
}
System.out.println(sum);
return sum;
}
public static void main(String[] args) {
try{
MethodTest mt = mock(MethodTest.class);
when(mt.tripleDot((String[])anyObject())).thenReturn("Hello world!");
System.out.println(mt.tripleDot(new String[]{"1","2"}));
}
catch (Exception e) {
System.out.println(e.getClass().toString() + ": " + e.getMessage());
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果print语句是:
System.out.println(mt.tripleDot(new String[]{"1"}));
Run Code Online (Sandbox Code Playgroud)
要么
System.out.println(mt.tripleDot("1"));
Run Code Online (Sandbox Code Playgroud)
它将打印"Hello world".
但如果print语句是:
System.out.println(mt.tripleDot(new String[]{"1","2"}));
Run Code Online (Sandbox Code Playgroud)
要么
System.out.println(mt.tripleDot("1","2"));
Run Code Online (Sandbox Code Playgroud)
它将打印"null".
我也尝试过调用时的变化,例如anyObject()或者anyString()无效.我不确定Mockito是否可以处理包含可变数量参数的方法调用的参数匹配器.它甚至可能吗?如果是这样,我应该怎么做才能使这项工作?
我在StackOverflow上的第一个问题.我希望能够做到这样的事情:
SomeClass mock = mock(SomeClass.class);
String methodName ="someMethod"; 或方法方法= ... someMethod ...
这两件事(模拟和方法)将结合起来执行以下操作:
当(mock.someMethod())thenReturn(空).
当然,'null'值会根据我的需要进行相应更改,但我想确定两件事:
1),它甚至有可能做一些像这样在Java中? 这 =将类对象和方法组合到methodCall中.
2)我怎么做这样的事情?
我无休止地研究了这个,我找不到任何东西.问题是即使这适用于常规类和常规方法(someClass和someMethod会聚在一起做someClass.someMethod()),请记住,这必须与模拟对象一起使用才能在when中使用( )打电话.
答案:when(method.invoke(mock)).thenReturn("Hello world."); 是正确的语法和反射确实在when()调用内工作.谢谢Kevin Welker!