[ How to reach to static method from class instance for mock ]
I need to stub Java.util.concurrent.Executors class newFixedThreadPool method and verify it.
Executors.newFixedThreadPool(executorServiceThreadCount, threadFactory)
I tried create a global Executors value for overriding from test fragment.
lazy val executors = Executors
But newFixedThreadPool method is not reachable from executors instance. What should i do for stubbing this method. And any best practise for this ? Thanks
Answer 1
You can use PowerMockito to mock static methods. Use the following annotations on top of your test class:
@RunWith(PowerMockRunner.class)
@PrepareForTest({Executors.class, ClassYouAreTesting.class})
and use the following code to mock the newFixedThreadPool method:
PowerMockito.mockStatic(Executors.class);
Mockito.when(Executors.newFixedThreadPool(5)).thenReturn(mockService);