我有一些使用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);
}
通过委派给
ManagedExecutorService
可以创建ExecutorService
:@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对其进行扩展。
希望这可以帮助!