如何模拟executorService.submit()

时间:2019-01-29 10:52:04

标签: unit-testing testing junit mockito powermock

如何在下面的场景中模拟executorService.submit()。我必须模拟

cacheController.someMethod();但是当调用submit方法时,它会创建一个线程和cacheController.someMethod();。永远不会被要求参加测试班。

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

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

1 个答案:

答案 0 :(得分:1)

基本上,您通过依赖来创建难以测试的代码

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

为了对此进行测试,您必须使用PowerMock(ito)暗魔法来控制此处对静态方法newFixedThreadPool(1)的调用。从理论上讲,这很不错,例如,请参见here

但是:通常,当您在基于Spring的环境中进行体面的单元测试时,您可能已经在使用另一个测试运行程序,以使@AutoWired在您的测试设置中正常工作。在其中添加PowerMock(ito)会使事情变得更加复杂,并且容易出错。

因此,真实的答案是:重做您的设计,以依赖该静态方法调用。如果将其转换为 normal 字段,则应该能够使用“标准”的模仿注入机制,如概述的here

最后:我也建议研究same thread executor。含义:不要模拟服务,而是注入一个特定的服务实例,该实例只是在同一线程上调用您的代码。然后,您可以获得更多的测试范围,但可以避免通常在单元测试中令人头疼的大多数多线程问题。