Avinash Kharche
Avinash Kharche

Reputation: 441

How to mock executorService.submit()

How can I mock executorService.submit() in the below scenerio. I have to mock

cacheController.someMethod(); but as submit method is called it creates a thread and cacheController.someMethod(); never gets called for test class.

@Autowired
CacheController cacheController;
protected static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(1);

EXECUTOR.submit(() -> {
        try {
            cacheController.someMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }
    });

Upvotes: 6

Views: 9867

Answers (1)

GhostCat
GhostCat

Reputation: 140457

Basically you created hard to test code by relying on

protected static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(1);

In order to test that, you would have to use PowerMock(ito) dark magic to gain control over that call to the static method newFixedThreadPool(1) here. In theory, that is nice and easy, see here for example.

But: typically, when you do decent unit testing for Spring based environments, then you are probably already using another test runner, to get that @AutoWired thing working in your test setup. Adding PowerMock(ito) to that makes things much more complicated, and prone to errors.

Thus, the real answer is: rework your design, to not rely on that static method call. If you turn that thing into a normal field, you should be able to use "standard" mockito injection mechanisms, like outlined here.

Finally: I would also suggest to look into a same thread executor. Meaning: dont mock the service, but inject a specific service instance that simply calls your code on the same thread. Then you get quite more test coverage, but you avoid the most multi threading issues that normally give headaches in unit tests.

Upvotes: 3

Related Questions