我有一个正在测试的模拟电梯的系统。我正在测试电梯是否到达特定楼层。这是我的测试代码:
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());
现在 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);
}
}
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++;}
如您所见,时间起着重要的作用。现在,根据我目前的测试,电梯不会移动。很明显我必须等待电梯移动,我怎么能在测试用例中做到这一点。我曾尝试将 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.
通常,当我对具有细微时序竞争条件的事物进行单元测试时,我在整个方法上使用 timeout
,然后我有一个自旋循环等待条件发生。
@Test(timeout = 10000)
public void testSomeTimingIssue() throws Exception {
while (!elevatorMoved) {
// test elevator
Thread.sleep(50);
}
}
关于java - 包含Thread.sleep的JUnit测试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21735487/