我有一些使用Java EE ManagedExecutorService
的服务(在Wildfly 9中)
WSO2 MDM - Mobile Device Management Admin Services
对于Mockito的测试,我想使用“普通”ExecutorService
public class FooService{
@Resource
ManagedExecutorService executorService;
}
此代码显然无法编译,因为@RunWith(MockitoJUnitRunner.class)
public class FooServiceTest{
@Spy
ManagedExecutorService executorService = Executors.newFixedThreadPool(5);
}
不是ExecutorService
。
在服务中使用ManagedExecutorService
时,测试运行没有错误,但Wildfly无法注入服务。
ExecutorService
可以通过委派给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
}
而不更改在Wildfly中运行的服务?
答案 0 :(得分: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
}
您也可以从junit setup()调用新的TestImpl()。此外,如果您想使其更灵活,那么您可以使用BaseImpl并同时使用DefaultImpl和TestImpl扩展它。
希望这有帮助!