How can I make a JUnit test wait?

Kylar picture Kylar · Apr 11, 2013 · Viewed 102.7k times · Source

I have a JUnit test that I want to wait for a period of time synchronously. My JUnit test looks like this:

@Test
public void testExipres(){
    SomeCacheObject sco = new SomeCacheObject();
    sco.putWithExipration("foo", 1000);
    // WAIT FOR 2 SECONDS
    assertNull(sco.getIfNotExipred("foo"));
}

I tried Thread.currentThread().wait(), but it throws an IllegalMonitorStateException (as expected).

Is there some trick to it or do I need a different monitor?

Answer

Muel picture Muel · Apr 11, 2013

How about Thread.sleep(2000); ? :)