gpt4 book ai didi

java - 在测试中用 ExecutorService 替换 ManagedExecutorService

转载 作者:搜寻专家 更新时间:2023-11-01 03:48:07 24 4
gpt4 key购买 nike

我有一些使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com