模拟自动连线的执行器服务

哈纳赫

抽象:

我有一个@Component使用自动连接的ExecutorService作为工作池的Spring 我正在使用JUnit和Mockito来测试组件的功能,并且需要模拟该Executor服务。对于其他自动连线的成员来说,这是微不足道的-通用助手和DAO层很容易被嘲笑,但是我需要一个真正的Executor Service。

码:

@RunWith(MockitoJUnitRunner.class)
public class MadeUpClassNameTest{

  @Mock
  private ExecutorService executor;

  @Before
  public void initExecutor() throws Exception{
      executor = Executors.newFixedThreadPool(2);
  }

  @InjectMocks
  private ASDF componentBeingAutowired;
...

单靠这是行不通的,结果invokeAll()始终是一个空列表。

尝试更明确地模拟executor方法也不起作用...

@Test
public void myTestMethod(){
    when(executor.invokeAll(anyCollection()))
        .thenCallRealMethod();
    ...
}

我得到了措辞含糊的例外:

您不能在验证或存根之外使用参数匹配器。

(我以为这是存根?)

可以提供一种thenReturn(Answer<>)方法,但是我想确保代码实际上可以与执行者一起使用,其中相当一部分代码专门用于映射Futures的结果。

问题我如何提供真实(或功能可用的模拟)执行器服务?或者,我在测试该组件时遇到的困难是否表示这是一个需要重构的不良设计,或者可能是不良的测试场景?

注意,我想强调的是我的问题不是要设置Mockito或Junit。其他模拟和测试正常工作。我的问题仅特定于上面的特定模拟。

使用:Junit 4.12,Mockito 1.10.19,Hamcrest 1.3

卢卡斯

我认为以下代码在注入Mock之后运行。

@Before
public void initExecutor() throws Exception{
  executor = Executors.newFixedThreadPool(2);
}

这将导致设置您的本地副本executor,但不会设置注入的副本

我建议您使用构造函数注入componentBeingAutowired并在单元测试中创建一个新的注入并排除Spring依赖项。然后,您的测试可能如下所示:

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
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章