2727import static org .junit .jupiter .api .Assertions .assertEquals ;
2828
2929import org .junit .jupiter .api .Test ;
30+ import java .util .concurrent .CountDownLatch ;
31+ import java .util .concurrent .TimeUnit ;
3032
3133/**
3234 * Add a field as a counter. Every time the callback method is called increment this field. Unit
@@ -39,19 +41,30 @@ class CallbackTest {
3941 private Integer callingCount = 0 ;
4042
4143 @ Test
42- void test () {
43- Callback callback = () -> callingCount ++ ;
44+ void test () throws InterruptedException {
45+ CountDownLatch latch = new CountDownLatch ( 1 ) ;
4446
45- var task = new SimpleTask ();
47+ CountDownLatch finalLatch = latch ;
48+ Callback callback = () -> {
49+ callingCount ++;
50+ finalLatch .countDown ();
51+ };
4652
47- assertEquals ( Integer . valueOf ( 0 ), callingCount , "Initial calling count of 0" );
53+ var task = new SimpleTask ( );
4854
4955 task .executeWith (callback );
5056
57+ latch .await (5 , TimeUnit .SECONDS );
58+
5159 assertEquals (Integer .valueOf (1 ), callingCount , "Callback called once" );
5260
61+ callingCount = 0 ;
62+ latch = new CountDownLatch (1 );
63+
5364 task .executeWith (callback );
5465
55- assertEquals (Integer .valueOf (2 ), callingCount , "Callback called twice" );
66+ latch .await (5 , TimeUnit .SECONDS );
67+
68+ assertEquals (Integer .valueOf (1 ), callingCount , "Callback called once again" );
5669 }
5770}
0 commit comments