I'm trying to write unit tests for this method:
public class ClassToTest{
....
public void execute() {
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(this::launch);
}
....
}
and I tried to mock Executors.newSingleThreadExecutor() to have an executorService that runs on the same thread as my tests, so that my assertions happens after the executions of the executorService and not before:
@RunWith(PowerMockRunner.class)
@PrepareForTest({
AnOtherClass.class,
Executors.class
})
public class TestClass {
@Before
public void setUp() throws Exception {
PowerMockito.mockStatic(Executors.class);
ExecutorService executorService = mock(ExecutorService.class);
implementAsDirectExecutor(executorService);
PowerMockito.when(Executors.newSingleThreadExecutor()).thenReturn(executorService);
}
private void implementAsDirectExecutor(ExecutorService executor) {
doAnswer(invocation -> {
Object[] args = invocation.getArguments();
Runnable runnable = (Runnable)args[0];
runnable.run();
return null;
}).when(executor).submit(any(Runnable.class));
}
@Test
public void testMethod() {
....
classToTest.execute();
.... //assert something
}
}
Problem :
Even with PowerMockito.when(Executors.newSingleThreadExecutor()).thenReturn(executorService);
the real method is called, and I don't get the mocked ExecutorService.