11

Is there a way to use Awaitility to assert that nothing has changed? I want to verify that a topic was not written to, but because there is no state change, Awaitility does not like this. E.g. this code gives the below error. Thanks

    @Test
    fun waitUntilListMightBePopulated() {

        val myTopic: List<String> = emptyList()

        await.atLeast(2, TimeUnit.SECONDS).pollDelay(Duration.ONE_SECOND).until {
            myTopic.isEmpty()
        }
    }
ConditionTimeoutException: Condition was evaluated in 1005478005 NANOSECONDS which is earlier than expected minimum timeout 2 SECONDS
Damo
  • 1,449
  • 3
  • 16
  • 29

2 Answers2

11

Yes, you can verify that using during method.
It is supported scince Awaitility 4.0.2 version.

For example:
In the below example, we will verify during 10 seconds, the topic will be maintained empty [not-changed].

await()
    .during(Duration.ofSeconds(10)) // during this period, the condition should be maintained true
    .atMost(Duration.ofSeconds(11)) // timeout
    .until (() -> 
        myTopic.isEmpty()           // the maintained condition
    );

Hint:
It is obvious that, the during timeout duration SHOULD BE less than atMost timeout duration [or DefaultTimeout value], otherwise, the test case will fail then throws a ConditionTimeoutException

Ahmed Nabil
  • 17,392
  • 11
  • 61
  • 88
1

Awaitility throws ConditionTimeoutException when timeout is reached. One way to check that nothing changed in a predetermined time is to look for a change and assert that exception is thrown.

Please note, that this solution is very slow because of the minimal waiting time for a successful result and carries disadvantages related to throwing exceptions (What are the effects of exceptions on performance in Java?).

@Test
public void waitUntilListMightBePopulated() {
    List<String> myTopic = new ArrayList<>();

    Assertions.assertThrows(ConditionTimeoutException.class,
        () -> await()
                .atMost(Duration.ofSeconds(2))
                .until(() -> myTopic.size() > 0)
    );
}