[英]Mockito - How to spy on Invocation argument in doAnswer
This is my first day writing Unit tests using Mockito and I might have started with a complex exercise. 这是我使用Mockito编写单元测试的第一天,我可能已经开始了一个复杂的练习。
Below is my class structure and I am writing tests for Class2.targetMethod(). 下面是我的类结构,我正在为Class2.targetMethod()编写测试。 Class1 static method modifies passed in object instead of returning any results. Class1静态方法修改传入的对象,而不返回任何结果。
class Class1 {
static void dbquery(OutParam out) {
// Complex code to fill in db results in OutParam object
}
}
class Class2 {
void targetMethod() {
OutParam p1 = new OutParam1();
Class1.dbquery(p1);
ResultSet rs = p1.getCursor();
...
}
}
Below is my setup for the tests: 以下是我的测试设置:
@RunWith(PowerMockRunner.class)
@PrepareForTest({Class1.class, Class2.class})
public class Class2Test {
@Before
public void setUp() throws Exception {
PowerMockito.mockStatic(Class1.class);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Exception {
OutParam result = (OutParam)invocation.getArguments()[1];
OutParam spy = spy(result);
ResultSet mockResult = mock(ResultSet.class);
doReturn(mockResult).when(spy.getCursor());
when(mockResult.getString("some_id")).thenReturn("first_id","second_id");
when(mockResult.getString("name")).thenReturn("name1","name2");
return null;
}
}).when(Class1.class, "dbquery", any());
}
}
However the tests fail with exception below - mainly due to "doReturn" line. 但是,测试失败并出现以下异常-主要是由于“ doReturn”这一行。
Any suggestions on this problem or if my approach is completely wrong. 关于此问题或我的方法完全错误的任何建议。
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, you naughty developer!
3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed
The syntax for: 语法:
doReturn(mockResult).when(spy.getCursor());
should be: 应该:
doReturn(mockResult).when(spy).getCursor();
By calling when
with only the spy
, and not spy.getCursor()
, you give Mockito a chance to temporarily deactivate getCursor
so you can stub it without calling the real thing. 通过调用when
只用spy
,而不是spy.getCursor()
你给一个的Mockito机会暂时停用getCursor
所以你可以存根时不调用真实的东西。 Though that doesn't seem to be important here, Mockito insists that you keep this pattern for calls to when
following doAnswer
(etc). 尽管这似乎在这里并不重要,但Mockito坚持要遵循doAnswer
(etc) when
调用模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.