Java如何从另一个模拟方法调用方法

时间:2015-12-16 14:51:45

标签: java unit-testing mockito powermock powermockito

是否可以从另一个模拟方法调用某个方法而不是使用Mockito或PowerMock返回值?

这是明确的例子:

我在生产类中有一个查询:

session.createQuery("update clause")
                    .setParameter("")
                    .executeUpdate();
session.flush();

在我的测试课中,我这样嘲笑:

Query q = mock(Query.class, "q");
when(session.createQuery("update lalala")).thenReturn(q);
when(q.executeUpdate()).thenReturn(something);

现在我不需要执行thenReturn(something),而是需要调用一个位于我的测试类中的void方法来模拟数据库行为。

即。

public void doSomething()
{
  // do smth
}

因此,在我的测试中,当调用q.executeUpdate时,也会调用doSomething()。

我搜索了任何可能的想法,但似乎无法弄明白。

2 个答案:

答案 0 :(得分:4)

您可以使用thenAnswer功能。请参阅documentation

when(q.executeUpdate()).thenAnswer( new Answer<Foo>() {
    @Override
    public Foo answer(InvocationOnMock invocation) throws Throwable {
      callYourOtherMethodHere();
      return something;
    }
} );

答案 1 :(得分:0)

您可以使用EasyMock执行类似的操作(也可以使用其他模拟工具)。

Query q = createMock(Query.class)
expect(q.createQuery("update lalala")).andDelegateTo(anObjectThatCalls_doSomething);
...