[英]JUnit testing method containing Thread.sleep
I have a system under test which is simulating elevators. 我有一个正在测试的系统,它模拟电梯。 I am testing whether the elevator arrives at a particular floor.
我正在测试电梯是否到达特定楼层。 This is the code of my test:
这是我测试的代码:
int chosenFloor=r.nextInt(6)+6;
lc.moveLift(0, chosenFloor); //moving lift 0 to the chosen floor
open=false;
floor=chosenFloor;
moving=false;
assertEquals(floor, lc.getLifts()[0].getFloor());
Now the method moveLift calls this piece of code: 现在方法moveLift调用这段代码:
lift.setMoving(true);
int fromFloor = lift.getFloor();
setLiftFloor(fromFloor);
lift.setMoving(true);
if (toFloor > fromFloor) {
for (int i = fromFloor; i < toFloor; i++) {
animateUp(i);
lift.setFloor(i);
}
} else {
for (int i = fromFloor; i > toFloor; i--) {
animateDown(i);
lift.setFloor(i);
}
}
And animateUp calls this method: animateUp调用此方法:
int lower = currentFloor * animationStepsPerFloor;
int upper = lower + animationStepsPerFloor - 1;
for (int i = 0; i < animationStepsPerFloor; i++) {
try {
Thread.sleep(50);
} catch (Exception e) {
e.printStackTrace();
}
lower++;
upper++;}
So as you can see, time plays an important factor. 如你所见,时间是一个重要因素。 Right now, with my current test, the lift does not move.
现在,根据我目前的测试,电梯不会移动。 It is obvious that I have to wait for the lift to move, how can I do it in a test case.
很明显,我必须等待电梯移动,我怎么能在测试用例中做到这一点。 I have tried placing Thread.sleep in my test case, but it's futile.
我试过在我的测试用例中放置Thread.sleep,但这是徒劳的。
It is obvious that I have to wait for the lift to move, how can I do it in a test case.
很明显,我必须等待电梯移动,我怎么能在测试用例中做到这一点。 I have tried placing Thread.sleep in my test case, but it's futile.
我试过在我的测试用例中放置Thread.sleep,但这是徒劳的。
Typically when I am doing unit tests on things that have subtle timing race conditions I use a timeout
on the entire method and then I have a spin loop waiting for the condition to occur. 通常当我对具有微妙定时竞争条件的事情进行单元测试时,我在整个方法上使用
timeout
,然后我有一个旋转循环等待条件发生。
@Test(timeout = 10000)
public void testSomeTimingIssue() throws Exception {
while (!elevatorMoved) {
// test elevator
Thread.sleep(50);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.