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

Java How to call a method from another mock method

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

这里举例说明:

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

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

在我的测试中 class 我是这样模拟的:

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

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

public void doSomething()
{
  // do smth
}

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

我用谷歌搜索了任何可能的想法,但似乎无法弄清楚。

你可以用 EasyMock 做这样的事情(也许也可以用其他模拟工具)。

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

您可以使用thenAnswer功能。见 documentation

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