How do I write a JUnit test case to test threads and events

前端 未结 7 856
无人共我
无人共我 2020-12-09 17:07

I have a java code which works in one (main) thread. From the main thread, i spawn a new thread in which I make a server call. After the server call is done, I am doing some

7条回答
  •  一整个雨季
    2020-12-09 17:34

    When your only problem is waiting for the result, use ExecutorService for spawning your threads. It can accept work jobs both as Runnable and Callable. When you use the latter, then you are given a Future object in return, that can be used to wait for the result. You should consider using ExecutorService anyway, as from what I understand, you create many threads, and this is a perfect use case for executor services.

    class AnyClass {
        private ExecutorService threadPool = Executors.newFixedThreadPool(5);
    
        public List> anyMethod() {
            List futures = new ArrayList<>();
    
            futures.add(threadPool.submit(() -> {
                // Do your job here
                return anyStatusCode;
            }));
    
            futures.add(threadPool.submit(() -> {
                // Do your other job here
                return anyStatusCode;
            }));
    
            return futures;
        }
    }
    

    And the test class:

    class TestAnyClass {
        @Test
        public void testAnyMethod() {
            AnyClass anyObject = new AnyClass();
    
            List> futures = anyObject.anyMethod();
            CompletableFuture[] completable = futures.toArray(new CompletableFuture[futures.size()]);
    
            // Wait for all
            CompletableFuture.allOf(completable).join();
        }
    }
    

提交回复
热议问题