2
我有一個模擬電梯的被測系統。我正在測試電梯是否到達特定樓層。這是我的測試代碼:包含Thread.sleep的JUnit測試方法
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放在我的測試用例中,但它是徒勞的。