我已经在网上阅读了很多文档和示例,但仍然不知道该怎么做。 (如果可以的话)。
我需要测试一个被其他线程调用的对象中的方法,它有时间要求。所以我最初的想法是创建一个 spy ,覆盖方法并完成任务,但问题是,我无法从 spy 访问测试方法变量。所以我无法从测试方法中获取从 System.currentTimeMillis()
返回的值并对其进行处理以获取时间差。
我会写一些描述情况的抽象代码,以便您更好地理解情况。
@Test
public void test()
{
Objectspied spy = Mockito.spy(new Objectspied(Parameters p));
long[] timesRetrieved = new long[numberOfCallsIExpect];
//here goes the tricky part
Mockito.doAnswer(new Answer<void>(){
@override
public methodCalledFromAnotherThread(int index)
{
//what i wish to do but can't do it
timesRetrieved[i] = System.currentTimeMilis();
}
}
).when(spy).methodCalledFromAnotherThread(anyInt);
//here initialize the thread who call it
//then proccess al time diferences and get sure they are what i've expected
}
public class AnotherThread
{
ObjectSpied reference;
public void run()
{
for (int i=0;i<repeat;i++)
{
reference.methodCalledFromAnotherThread(i);
Thread.sleep(1000);
}
}
}
我是 Mockito 的新手,所以我知道语法完全错误,但我可以自己修复它,我只需要知道:
- 有什么方法可以用 Mockito 做到这一点吗?
- 如果是这样,你能给我指出正确的方向吗?
最佳答案
这样应该没问题。只要确保:
1) 你将数组标记为final
2)正确实现回答接口(interface)方法
final long[] timesRetrieved = new long[size];
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
int index = invocationOnMock.getArgumentAt(0, Integer.class);
timesRetrieved[index] = System.currentTimeMillis();;
return null;
}
}
).when(spy).methodCalledFromAnotherThread(Mockito.anyInt());
关于java - 使用 mockito 验证调用之间的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47552000/