在测试中将 ManagedExecutorService 替换为 ExecutorService



我有一些使用Java EE ManagedExecutorService的服务(在Wildfly 9中)

public class FooService{
    @Resource
    ManagedExecutorService executorService;
}

对于Mockito的测试,我想使用"正常"ExecutorService

@RunWith(MockitoJUnitRunner.class)
public class FooServiceTest{
   @Spy
   ManagedExecutorService executorService = Executors.newFixedThreadPool(5);
}

这段代码显然不能编译,因为ExecutorService不是ManagedExecutorService

在服务中使用ExecutorService时,测试运行没有错误,但随后 Wildfly 无法注入服务。

public class FooService{
    @Resource
    ExecutorService executorService;
}
@RunWith(MockitoJUnitRunner.class)
public class FooServiceTest {
   @Spy
   ExecutorService executorService = Executors.newFixedThreadPool(5);
}
可以通过

委托给ExecutorService来创建ManagedExecutorService

@Spy
ManagedExecutorService executorService = new ManagedExecutorService() {
   ExecutorService executorService = Executors.newFixedThreadPool(5);
   @Override
   public void shutdown() {
       executorService.shutdown();
   }
   // delegate for all (12) methods
}

有没有更简单的方法可以在测试中使用ExecutorService而不更改在 Wildfly 中运行的服务?

我使用注入模式:

class DefaultImpl {
 static DefaultFactory me;
 static DefaultFactory getCurrentInstance()
  { if (me == null) {
     me = new DefaultFactory();
    }
    return me;
  }
void setCurrentInstance(DefaultFactory df){
  me = df;
}
 ExecutorService getExecutorService(){
   // lookup and return ManagedExecutorService
 }
}
class TestImpl extends DefaultImpl{
  TestImpl(){
    DefaultFactory.setCurrentInstance(this); <-- this now sets your TestImpl for any call
  }
  ExecutorService getExecutorService(){
    ExecutorService executorService = Executors.newFixedThreadPool(5);
    return executorService;
  }
}
//junit
@Test
void someTest(){
 new TestImpl();
 // do something all your calls will use non managed executor service
}

你也可以从 junit setup() 调用新的 TestImpl()。另外,如果你想让它更灵活,那么你可以有一个BaseImpl,并让DefaultImpl和TestImpl扩展它。

希望这有帮助!

相关内容

  • 没有找到相关文章

最新更新