Mockito 更改非 void 方法的参数值

Raj*_*ure 6 java mockito

我正在尝试模拟一个签名为的方法:

public A doSomething(B b, String str){}
Run Code Online (Sandbox Code Playgroud)

我尝试使用 doAnswer 更新 str 值。但是,此方法返回具有条件设置的值的对象 A。我无法找到一种方法来设置要传递给此方法的特定 str 值。任何人都可以让我知道这是如何实现的吗?我不能在我的项目中使用 powermock。

Jef*_*ica 4

对于一次性模拟,您可以使用InvocationOnMock.getArguments来获取 的值str

doAnswer(new Answer<Foo>() {
  @Override public Foo answer(InvocationOnMock invocation) {
    A a = mock(A.class);
    when(a.someMethod()).thenReturn((String) (invocation.getArguments()[0]));
    return a;
  }
}).when(yourObject).doSomething(any(B.class), anyString());

// or with Java 8:
doAnswer(invocation => {
  A a = mock(A.class);
  when(a.someMethod()).thenReturn((String) (invocation.getArguments()[0]));
  return a;
}).when(yourObject).doSomething(any(), anyString());
Run Code Online (Sandbox Code Playgroud)

...但只要该方法是可模拟的(可见且非最终的),您也可以将新方法内联编写为匿名内部子类(或其他地方定义的静态子类),这可以完成相同的事情,而无需那么多转换和 Mockito 语法:

YourObject yourObject = new YourObject() {
  @Override public A someMethod(B b, String str) {
    A a = mock(A.class);
    when(a.someMethod()).thenReturn(str);
    return a;
  }
};
Run Code Online (Sandbox Code Playgroud)