如何让JUnit Test等待?

时间:2022-12-08 20:45:42

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

我有一个JUnit测试,我想要等待一段时间,同步。我的JUnit测试看起来像这样:

@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?

我尝试了Thread.currentThread()。wait(),但它抛出了IllegalMonitorStateException(如预期的那样)。是否有一些技巧,或者我需要一个不同的显示器?

3 个解决方案

#1


93  

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

Thread.sleep(2000); ? :)

#2


38  

Thread.sleep() could work in most cases, but usually if you're waiting, you are actually waiting for a particular condition or state to occur. Thread.sleep() does not guarantee that whatever you're waiting for has actually happened.

Thread.sleep()在大多数情况下都可以工作,但通常如果你在等待,你实际上正在等待特定的条件或状态发生。 Thread.sleep()不保证您正在等待的任何事实实际发生。

If you are waiting on a rest request for example maybe it usually return in 5 seconds, but if you set your sleep for 5 seconds the day your request comes back in 10 seconds your test is going to fail.

如果您正在等待休息请求,例如它通常可以在5秒内返回,但如果您在10秒内将请求恢复到5秒钟,那么您的测试将失败。

To remedy this JayWay has a great utility called Awatility which is perfect for ensuring that a specific condition occurs before you move on.

为了解决这个问题,JayWay有一个很棒的实用程序叫做Awatility,它非常适合在你继续前进之前确保特定情况发生。

It has a nice fluent api as well

它也有一个漂亮的流畅api

await().until(() -> 
{
    return yourConditionIsMet();
});  

https://github.com/jayway/awaitility

https://github.com/jayway/awaitility

#3


3  

You could also use the CountDownLatch object like explained here.

您也可以使用CountDownLatch对象,如此处所述。

#1


93  

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

Thread.sleep(2000); ? :)

#2


38  

Thread.sleep() could work in most cases, but usually if you're waiting, you are actually waiting for a particular condition or state to occur. Thread.sleep() does not guarantee that whatever you're waiting for has actually happened.

Thread.sleep()在大多数情况下都可以工作,但通常如果你在等待,你实际上正在等待特定的条件或状态发生。 Thread.sleep()不保证您正在等待的任何事实实际发生。

If you are waiting on a rest request for example maybe it usually return in 5 seconds, but if you set your sleep for 5 seconds the day your request comes back in 10 seconds your test is going to fail.

如果您正在等待休息请求,例如它通常可以在5秒内返回,但如果您在10秒内将请求恢复到5秒钟,那么您的测试将失败。

To remedy this JayWay has a great utility called Awatility which is perfect for ensuring that a specific condition occurs before you move on.

为了解决这个问题,JayWay有一个很棒的实用程序叫做Awatility,它非常适合在你继续前进之前确保特定情况发生。

It has a nice fluent api as well

它也有一个漂亮的流畅api

await().until(() -> 
{
    return yourConditionIsMet();
});  

https://github.com/jayway/awaitility

https://github.com/jayway/awaitility

#3


3  

You could also use the CountDownLatch object like explained here.

您也可以使用CountDownLatch对象,如此处所述。