Is power mockito thread safe?

154 views
Skip to first unread message

Free Andy

unread,
Dec 14, 2018, 2:41:06 PM12/14/18
to PowerMock
The Mockito FAQ indicates it is safe to let multiple threads access a mock as long as stubbing/verification is all done on the same thread.  

For healthy scenarios Mockito plays nicely with threads. For instance, you can run tests in parallel to speed up the build. Also, you can let multiple threads call methods on a shared mock to test in concurrent conditions. Check out a timeout() feature for testing concurrency.
However Mockito is only thread-safe in healthy tests, that is tests without multiple threads stubbing/verifying a shared mock. Stubbing or verification of a shared mock from different threads is NOT the proper way of testing because it will always lead to intermittent behavior. In general, mutable state + assertions in multi-threaded environment lead to random results. If you do stub/verify a shared mock across threads you will face occasional exceptions like: WrongTypeOfReturnValue, etc.


Is the same true for PowerMock? 


public class Support {
        public void say(final String word) {
                System.err.println("!!!! " + word + " !!!!");
        }
}

public class Service {
        private final Support support = new Support();

        public void doSomething() {
                support.say("hello");
        }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(Service.class)
public class ServiceTest {

        @Mock
        private Support support;

        @Before
        public void setup() throws Exception {
                PowerMockito.whenNew(Support.class).withNoArguments().thenReturn(support);
        }

        @Test
        public void doSomethingNoThreads() throws Exception {
                new Service().doSomething();
                verify(support).say("hello");
        }

        @Test
        public void doSomethingThreaded() throws Exception {

                javax.swing.SwingUtilities.invokeAndWait(() -> {
                        new Service().doSomething();
                });

                verify(support).say("hello");
        }
}

Reply all
Reply to author
Forward
0 new messages