My project uses JUnit
, Mockito
, PowerMockito
to create a unit test. The code as below:
public class FirstController {
public void doSomething() {
ServiceExecutor.execute();
}
}
public class ServiceExecutor {
private static final List<Service> services = Arrays.asList(
new Service1(),
new Service2(),
...
);
public static void execute() {
for (Service s : services) {
s.execute();
}
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({ServiceExecutor.class})
public class FirstControllerTest {
@Before
public void prepareForTest() {
PowerMockito.mockStatic(ServiceExecutor.class);
PowerMockito.doNothing().when(ServiceExecutor.class)
}
@Test
public void doSomethingTest() {
FirstController firstController = new FirstController();
firstController.doSomething();
PowerMockito.verifyStatic(ServiceExecutor.class, Mockito.times(1));
}
}
The full source code of this issue: https://github.com/gpcodervn/Java-Tutorial/tree/master/UnitTest
I want to verify the ServiceExecutor.execute()
method which was run.
I tried to mock ServiceExecutor
and doNothing()
when the execute()
method is called. But I have a problem with the private static final List<Service> services
in the ServiceExecutor
. It always constructs the new instance for each Service. Each service is longer to create the new instance and I don't know how many Service they will have later if I mock each Service
.
Do you have any idea to verify ServiceExecutor.execute()
in FirstController
without run any method in ServiceExecutor
?