我正在尝试模拟一个签名为:
的方法public A doSomething(B b, String str){}
我尝试使用doAnswer更新str值。但是,此方法返回对象A,其值有条件地设置。我无法找到一种方法来设置要传递给此方法的特定str值。谁能告诉我这是如何实现的?我不能在我的项目中使用powermock。
答案 0 :(得分:1)
对于一次性模拟,您可以使用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());
...但只要该方法是可模拟的(可见和非最终),您也可以将新方法内联编写为匿名内部子类(或其他地方定义的静态子类),这可以完成同样的事情没有那么多的演员和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;
}
};