Xentios
Xentios

Reputation: 80

How to get a success with Junit and timeout?

@Test (expected=TimeoutException.class,timeout=1000)
public void fineForFiveSeconds() {
    foo.doforever();
    fail("This line should never reached");
}

This is my test code. All I want is to run doforever() for some time period then make the test succeed.

Upvotes: 2

Views: 2090

Answers (1)

nrainer
nrainer

Reputation: 2623

Try this:

Execute the logic in a thread, sleep and check if the thread is still alive.

@Test
public void fineForFiveSeconds() throws InterruptedException {
  Thread thread = new Thread() {
    @Override
    public void run() {
      foo.doforever();
    }
  };

  thread.start();

  //Let the current thread sleep (not the created thread!)
  Thread.sleep(5000);

  assertTrue(thread.isAlive());
}

Upvotes: 4

Related Questions