How should I unit test threaded code?

后端 未结 26 1731
悲&欢浪女
悲&欢浪女 2020-11-22 04:09

I have thus far avoided the nightmare that is testing multi-threaded code since it just seems like too much of a minefield. I\'d like to ask how people have gone about test

26条回答
  •  情话喂你
    2020-11-22 04:51

    If you are testing simple new Thread(runnable).run() You can mock Thread to run the runnable sequentially

    For instance, if the code of the tested object invokes a new thread like this

    Class TestedClass {
        public void doAsychOp() {
           new Thread(new myRunnable()).start();
        }
    }
    

    Then mocking new Threads and run the runnable argument sequentially can help

    @Mock
    private Thread threadMock;
    
    @Test
    public void myTest() throws Exception {
        PowerMockito.mockStatic(Thread.class);
        //when new thread is created execute runnable immediately 
        PowerMockito.whenNew(Thread.class).withAnyArguments().then(new Answer() {
            @Override
            public Thread answer(InvocationOnMock invocation) throws Throwable {
                // immediately run the runnable
                Runnable runnable = invocation.getArgumentAt(0, Runnable.class);
                if(runnable != null) {
                    runnable.run();
                }
                return threadMock;//return a mock so Thread.start() will do nothing         
            }
        }); 
        TestedClass testcls = new TestedClass()
        testcls.doAsychOp(); //will invoke myRunnable.run in current thread
        //.... check expected 
    }
    

提交回复
热议问题