Chris Smith
Chris Smith

Reputation: 3012

How are timeouts handled in JUnit?

Say I have the following test:

@Test(timeout = 1)
public void test(){
  while(true){}
}

This simulates a test that would take a long time to return, not from sleeping, but from raw calculation time. How does the test exit? If I create a thread and try the same thing, it does not compile.

public static void main(String[] args) {
    Thread thread = new Thread() {
        public void run() {
            try {
                while (true) {
                }
            } catch (InterruptedException e) {//Exception 'java.lang.InterruptedException' is never thrown in the corresponding try block'
                e.printStackTrace();
            }
        }
    };
    thread.start();
    thread.interrupt();
}

I can even attempt to replicate the implementation, but it still does not interrupt the thread:

public static void main(String[] args) {
    Thread thread = new Thread() {
        public void run() {
            try {
                doTest();
            } catch (InterruptedException throwable) {
                System.out.println("interrupted");
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }

        private void doTest() throws Throwable {
            while (true) {
            }
        }
    };
    thread.start();
    thread.interrupt();
}

The java.lang.Exception: test timed out after 1 milliseconds exception claims to be originating strait from the while loop when running the regular test.

I am confused as to how the test is 'interrupted', but I cannot do the same with a regular thread. How is this 'interrupting' feature implemented in JUnit?

Upvotes: 0

Views: 622

Answers (1)

Related Questions