我有一个类,我想测试一个方法(executeLocal):
public class SDExecuter {
...
public boolean executeLocal() {
steps++;
resetDisturbance();
for (;;) {
try {
Event event = initialEventSequence.getFirst();
if (event.getActualEventTime() < timeManager.roundLocaTime(steps
* timeManager.getTps())) {
initialEventSequence.remove(event);
calculateIntervalBetweenEvents(event);
actualizedEventSequence.add(event);
continue;
}
informWithDisturbanceTorque();
break;
} catch (NoSuchElementException nsee) {
informWithDisturbanceTorque();
return true;
}
}
return false;
}
...
public void informWithDisturbanceTorque() {
if (hasDisturbed) {
disturbanceControl.setDistrubanceTorque(disturbanceTorqueVector);
}
}
...
}
具体来说,我想测试方法informWithDisturbanceTorque()的调用次数,以及方法setDistrubanceTorque的调用次数:
public class DisturbanceControl{
...
public void setDistrubanceTorque(VectorColumn3d disturbanceTorqueVector){
System.out.println("have a call with argument: " + disturbanceTorqueVector);
this.disturbanceTorqueVector = disturbanceTorqueVector;
}
...
}
此方法在调用方法时打印带有接收参数的消息。
我为该类的对象制作了一个模拟间谍:
spyDisturbanceControl = spy(new DisturbanceControl(null));
并对控制台反映出来的方法进行一些调用:
have a call with argument: {{-1.0}, {0.0}, {-1.0}}
have a call with argument: {{0.0}, {-1.0}, {0.0}}
问题是:当我在以下帮助下验证呼叫次数时:
@Test
public void executeLocalTest() {
for (int i = 0; i < 20; i++) {
sdExecuter.executeLocal();
if (timeManager.getStepNumber() == eventTact[2]) {
verify(spyDisturbanceControl, times(1)).setDistrubanceTorque(
new VectorColumn3d(-1.0d, 0.0d, -1.0d));
}
if (timeManager.getStepNumber() == eventTact[3]) {
verify(spyDisturbanceControl, times(1)).setDistrubanceTorque(
new VectorColumn3d(0.0d, -1.0d, 0.0d));
}
timeManager.makeTimeStep();
}
}
测试结束时出现错误:
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.579 sec <<< FAILURE!
executeLocalTest(test.SDExecuterTest) Time elapsed: 0.5 sec <<< FAILURE!
org.mockito.exceptions.verification.TooManyActualInvocations:
disturbanceControl.setDistrubanceTorque(
{{0.0}, {-1.0}, {0.0}}
);
Wanted 1 time:
-> at test.SDExecuterTest.executeLocalTest(SDExecuterTest.java:92)
But was 2 times. Undesired invocation:
-> at test.SDExecuter.informWithDisturbanceTorque(SDExecuter.java:197)
at test.SDExecuterTest.executeLocalTest(SDExecuterTest.java:92)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)