簡體   English   中英

包含Thread.sleep的JUnit測試方法

[英]JUnit testing method containing Thread.sleep

我有一個正在測試的系統,它模擬電梯。 我正在測試電梯是否到達特定樓層。 這是我測試的代碼:

    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,但這是徒勞的。

很明顯,我必須等待電梯移動,我怎么能在測試用例中做到這一點。 我試過在我的測試用例中放置Thread.sleep,但這是徒勞的。

通常當我對具有微妙定時競爭條件的事情進行單元測試時,我在整個方法上使用timeout ,然后我有一個旋轉循環等待條件發生。

@Test(timeout = 10000)
public void testSomeTimingIssue() throws Exception {
    while (!elevatorMoved) {
       // test elevator
       Thread.sleep(50);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM