Saturday, October 24, 2015

Mocking ExecutorService to Run Synchronously

Earlier I wrote about a technique for executing code synchronously in an ExecutorService. Here's an alternate approach that uses the Mockito framework to accomplish the same result, but without requiring any supporting code.

                ExecutorService executorService = Mockito.mock(ExecutorService.class);
                
                Mockito.when(executorService.submit(Mockito.argThat(new ArgumentMatcher<Runnable>() {
                    @Override
                    public boolean matches(Object argument) {
                        Runnable runnable = (Runnable) argument;
                        try {
                            runnable.run();
                        } catch (Exception e) {
                            e.printStackTrace();
                            Assert.fail();
                        }
                        return true;
                    }

                }))).thenReturn(Mockito.mock(Future.class));

When a Runnable is submitted to the ExecutorService, the mock simply calls the run method, no threads involved. This can also be adapted for use with Callable for a bit more sophistication. Now just inject the ExecutorService and invoke the code

No comments:

Post a Comment