在测试中用 ExecutorService 替换 ManagedExecutorService

use*_*547 5 java concurrency mockito wildfly jakarta-ee

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

public class FooService{
    @Resource
    ManagedExecutorService executorService;
}
Run Code Online (Sandbox Code Playgroud)

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

@RunWith(MockitoJUnitRunner.class)
public class FooServiceTest{
   @Spy
   ManagedExecutorService executorService = Executors.newFixedThreadPool(5);
}
Run Code Online (Sandbox Code Playgroud)

这段代码显然无法编译,因为 anExecutorService不是ManagedExecutorService.

当使用ExecutorService在服务上,没有错误的测试运行,但随后Wildfly不能注入服务。

public class FooService{
    @Resource
    ExecutorService executorService;
}

@RunWith(MockitoJUnitRunner.class)
public class FooServiceTest {
   @Spy
   ExecutorService executorService = Executors.newFixedThreadPool(5);
}
Run Code Online (Sandbox Code Playgroud)

可以ManagedExecutorService通过委托给 a来创建a ExecutorService

@Spy
ManagedExecutorService executorService = new ManagedExecutorService() {

   ExecutorService executorService = Executors.newFixedThreadPool(5);
   @Override
   public void shutdown() {
       executorService.shutdown();
   }

   // delegate for all (12) methods
}
Run Code Online (Sandbox Code Playgroud)

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

don*_*lys 0

我使用注入模式:

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
}
Run Code Online (Sandbox Code Playgroud)

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

希望这可以帮助!