JHa*_*ach 3 spring unit-testing executorservice mockito
抽象:
我有一个Spring @Component使用自动装配的ExecutorService作为工作池.我正在使用JUnit和Mockito来测试组件的功能,我需要模拟Executor服务.对于其他自动装配的成员来说这是微不足道的 - 通用助手,例如DAO层很容易被模拟,但我需要一个真正的 Executor服务.
码:
@RunWith(MockitoJUnitRunner.class)
public class MadeUpClassNameTest{
@Mock
private ExecutorService executor;
@Before
public void initExecutor() throws Exception{
executor = Executors.newFixedThreadPool(2);
}
@InjectMocks
private ASDF componentBeingAutowired;
...
Run Code Online (Sandbox Code Playgroud)
仅此一项不起作用,结果invokeAll()始终是一个空列表.
试图更明确地模拟执行器方法也不起作用......
@Test
public void myTestMethod(){
when(executor.invokeAll(anyCollection()))
.thenCallRealMethod();
...
}
Run Code Online (Sandbox Code Playgroud)
我得到了隐藏的措辞异常:
您不能在验证或存根之外使用参数匹配器.
(我以为这是一个存根?)
我可以提供一种thenReturn(Answer<>)方法,但我想确保代码实际上与执行者一起工作,相当一部分代码专门用于映射Futures的结果.
问题 如何提供真实(或功能可用的模拟)Executor服务?或者,我是否难以测试这个组件,这表明这是一个需要重构的糟糕设计,或者可能是一个糟糕的测试场景?
注意 我想强调我的问题是没有设置Mockito或Junit.其他模拟和测试工作正常.我的问题仅针对上面的特定模拟.
使用:Junit 4.12,Mockito 1.10.19,Hamcrest 1.3
我认为以下代码在注入Mock之后运行.
@Before
public void initExecutor() throws Exception{
executor = Executors.newFixedThreadPool(2);
}
Run Code Online (Sandbox Code Playgroud)
这会导致您的本地副本executor被设置,但不会被注入.
我建议在你的单元测试中使用构造函数注入并在componentBeingAutowired其中创建一个新的依赖项.您的测试可能如下所示:
public class MadeUpClassNameTest {
private ExecutorService executor;
@Before
public void initExecutor() throws Exception {
executor = Executors.newFixedThreadPool(2);
}
@Test
public void test() {
ASDF componentBeingTested = new ASDF(executor);
... do tests
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6801 次 |
| 最近记录: |