[英]Mockito - How to spy on Invocation argument in doAnswer
这是我使用Mockito编写单元测试的第一天,我可能已经开始了一个复杂的练习。
下面是我的类结构,我正在为Class2.targetMethod()编写测试。 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();
...
}
}
以下是我的测试设置:
@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());
}
}
但是,测试失败并出现以下异常-主要是由于“ doReturn”这一行。
关于此问题或我的方法完全错误的任何建议。
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
语法:
doReturn(mockResult).when(spy.getCursor());
应该:
doReturn(mockResult).when(spy).getCursor();
通过调用when
只用spy
,而不是spy.getCursor()
你给一个的Mockito机会暂时停用getCursor
所以你可以存根时不调用真实的东西。 尽管这似乎在这里并不重要,但Mockito坚持要遵循doAnswer
(etc) when
调用模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.