java - 在测试中用 ExecutorService 替换 ManagedExecutorService

标签 java jakarta-ee concurrency mockito wildfly

我有一些使用 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 无法注入(inject)服务。

public class FooService{
    @Resource
    ExecutorService executorService;
}

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

可以通过委托(delegate)给 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 中运行的服务?

最佳答案

我使用注入(inject)模式:

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() 调用 new TestImpl()。另外,如果你想让它更灵活,那么你可以有一个 BaseImpl 并让 DefaultImpl 和 TestImpl 扩展它。

希望这对您有所帮助!

关于java - 在测试中用 ExecutorService 替换 ManagedExecutorService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37722360/

相关文章:

java - Oracle 序列创建了两次。 ORA-00955 : name is already used by an existing object

java - 将表 JTable 中的空单元格读入数组

java - weblogic 服务器/其他资源上的哪个 jar 可能具有类 : oracle. security.jps.ee.http.JpsFilter?

servlets - 有没有办法创建一个具有两个 url 路径的 servlet?

c++ - 我们可以用 2 个或更多无锁容器原子地做一些事情而不锁定两者吗?

scala - 带有 RateLimiter 的 ExecutionContext

java - 在 Java 中使用复杂类声明泛型变量

java - 如何使用 guice 注入(inject)器动态绑定(bind)映射

serialization - 当通过远程 EJB 从数据库加载数据时,Java Web Start 应用程序会出现 MARSHAL 异常

concurrency - 如何保证多个子进程的信号传递