简体   繁体   中英

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:

    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:

    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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM