我有一个类 Handler.java
它有2个公共(public)方法update(), fetch()
在实际的 update() 实现中,我调用了公共(public)方法 fetch()
fetch() 依次调用服务。
所以现在我必须编写一个 testUpdate() 来模拟公共(public)方法调用,即 fetch()
因为它不是静态的,所以我尝试创建另一个 Handler.java 实例作为模拟,即
private Handler handler;
@Mocked
private Handler mockedHandler;
现在使用 mockedHandler,我在 testUpdate() 中设置以下代码
new NonStrictExpectations(){
mockedHandler.fetch();
returns(response);
};
handler.update();
现在,我希望 mockedhandler 用于调用 fetch() 和处理程序实例用于调用 update()。
但是当我运行对 update() 的实际方法调用时,它也被模拟了!!!
i.e. handler.update(); is not at all going to the update().
帮我模拟我在 update() 中调用的第二个公共(public)方法
谢谢
最佳答案
在我看来,您应该模拟从 Handler#fetch()
内部调用的服务类,而不是模拟 fetch()
方法。
无论如何,模拟一个类的一些方法而不模拟其他方法称为部分模拟。在 JMockit 中,您通常会为此使用 NonStrictExpectations(Object...)
构造函数,如以下示例测试所示:
@Test
public void handlerFetchesSomethingOnUpdate()
{
final Handler handler = new Handler();
new NonStrictExpectations(handler) {{
handler.fetch(); result = response;
}};
handler.update();
}
关于java - 使用 Jmockit 模拟公共(public)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19925377/