How to use JUnit to test asynchronous processes

前端 未结 18 1648
小蘑菇
小蘑菇 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:54

    This is what I'm using nowadays if the test result is produced asynchronously.

    public class TestUtil {
    
        public static  R await(Consumer> completer) {
            return await(20, TimeUnit.SECONDS, completer);
        }
    
        public static  R await(int time, TimeUnit unit, Consumer> completer) {
            CompletableFuture f = new CompletableFuture<>();
            completer.accept(f);
            try {
                return f.get(time, unit);
            } catch (InterruptedException | TimeoutException e) {
                throw new RuntimeException("Future timed out", e);
            } catch (ExecutionException e) {
                throw new RuntimeException("Future failed", e.getCause());
            }
        }
    }
    

    Using static imports, the test reads kinda nice. (note, in this example I'm starting a thread to illustrate the idea)

        @Test
        public void testAsync() {
            String result = await(f -> {
                new Thread(() -> f.complete("My Result")).start();
            });
            assertEquals("My Result", result);
        }
    

    If f.complete isn't called, the test will fail after a timeout. You can also use f.completeExceptionally to fail early.

提交回复
热议问题