简体   繁体   中英

JUnit and InterruptedException

I found the following example in JUnit documentation:

public static class HasGlobalLongTimeout {

    @Rule
    public Timeout globalTimeout= new Timeout(20);

    @Test
    public void run1() throws InterruptedException {
        Thread.sleep(100);
    }

    @Test
    public void infiniteLoop() {
        while (true) {}
    }
}

I understand that whenever JUnit tries to interrupt the first test, it will interrupt the thread where it is running on, and it will throw an InterruptedException, leading to the test being finished.

But what about the second test (infiniteLoop)? It is not throwing anything. How is it stopped after the timeout?

The timeout rule runs each test in a separate thread, and waits for the timeout. After the timeout, the thread is interrupted. The test runner will then continue on to the next test. It doesn't wait for any response to the interrupt, so the test is free to continue running in the background.

infiniteLoop won't throw any InterruptedException but continue running while any remaining tests are run.

Once all the tests have finished, then the JVM running the tests will typically terminate, along with all the threads within it. Either because the threads are marked as daemon threads, or via a System.exit call.

See the source code:

It should be thrown in both tests, the @Rule annotation attaches a timer to each test. If the test runs more than 20ms an exception is fired. So in your program the second test should fire an InterruptedException as well.

I tried the following code and it works properly (ie both tests fails due to timeout of 20ms) I am using Java 8 and JUnit 4.12.

import java.util.concurrent.TimeUnit;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;

public class HasGlobalLongTimeout {

    @Rule
    public Timeout globalTimeout = new Timeout(20, TimeUnit.MILLISECONDS);

    @Test
    public void run1() throws InterruptedException {
        Thread.sleep(100);
    }

    @Test
    public void infiniteLoop() {
        while (true) {
        }
    }
}

Notice that I remove the static modifier in the class declaration (as far as I know it is not allowed for classes) and I changed the Timeout declaration (that one is deprecated currently).

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