Java snippets - LiveStone/knowledge-base GitHub Wiki

JUnit: Test spawned thread
    @Test
    public void childThreadContext() throws Exception {
        String value = "value";
        IncomingRequestIdHolder.set(new MockHttpServletRequest(), value);

        final String retValue = IncomingRequestIdHolder.get();
        Assert.assertSame(value, retValue);

        AsyncTester t = new AsyncTester(() -> {
            final String valFromChildThread = IncomingRequestIdHolder.get();
            Assert.assertSame(value, valFromChildThread);
        });
        t.start();
        t.test();
    }


    private static class AsyncTester {
        private Thread thread;
        private AssertionError exc;

        public AsyncTester(final Runnable runnable){
            thread = new Thread(() -> {
                try{
                    runnable.run();
                } catch(AssertionError e){
                    exc = e;
                }
            });
        }

        public void start(){
            thread.start();
        }

        public void test() throws InterruptedException{
            thread.join();
            if (exc != null)
                throw exc;
        }
    }
⚠️ **GitHub.com Fallback** ⚠️