How to use JUnit to test asynchronous processes

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

    I prefer use wait and notify. It is simple and clear.

    @Test
    public void test() throws Throwable {
        final boolean[] asyncExecuted = {false};
        final Throwable[] asyncThrowable= {null};
    
        // do anything async
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // Put your test here.
                    fail(); 
                }
                // lets inform the test thread that there is an error.
                catch (Throwable throwable){
                    asyncThrowable[0] = throwable;
                }
                // ensure to release asyncExecuted in case of error.
                finally {
                    synchronized (asyncExecuted){
                        asyncExecuted[0] = true;
                        asyncExecuted.notify();
                    }
                }
            }
        }).start();
    
        // Waiting for the test is complete
        synchronized (asyncExecuted){
            while(!asyncExecuted[0]){
                asyncExecuted.wait();
            }
        }
    
        // get any async error, including exceptions and assertationErrors
        if(asyncThrowable[0] != null){
            throw asyncThrowable[0];
        }
    }
    

    Basically, we need to create a final Array reference, to be used inside of anonymous inner class. I would rather create a boolean[], because I can put a value to control if we need to wait(). When everything is done, we just release the asyncExecuted.

提交回复
热议问题