How to Succeed 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 it doforever()

for a period of time to make the test successful.

+3


source to share


1 answer


Try the following:

Execute logic on the thread, sleep and check if the thread is 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());
}

      

+3


source







All Articles