How to use JUnit to test asynchronous processes

前端 未结 18 1652
小蘑菇
小蘑菇 2020-11-29 15:06

How do you test methods that fire asynchronous processes with JUnit?

I don\'t know how to make my test wait for the process to end (it is not exactly a unit test, it

18条回答
  •  一个人的身影
    2020-11-29 15:40

    There's nothing inherently wrong with testing threaded/async code, particularly if threading is the point of the code you're testing. The general approach to testing this stuff is to:

    • Block the main test thread
    • Capture failed assertions from other threads
    • Unblock the main test thread
    • Rethrow any failures

    But that's a lot of boilerplate for one test. A better/simpler approach is to just use ConcurrentUnit:

      final Waiter waiter = new Waiter();
    
      new Thread(() -> {
        doSomeWork();
        waiter.assertTrue(true);
        waiter.resume();
      }).start();
    
      // Wait for resume() to be called
      waiter.await(1000);
    

    The benefit of this over the CountdownLatch approach is that it's less verbose since assertion failures that occur in any thread are properly reported to the main thread, meaning the test fails when it should. A writeup that compares the CountdownLatch approach to ConcurrentUnit is here.

    I also wrote a blog post on the topic for those who want to learn a bit more detail.

提交回复
热议问题