【问题标题】:Mock a public method using Jmockit使用 Jmockit 模拟公共方法
【发布时间】:2013-11-24 09:03:51
【问题描述】:

我有一个类 Handler.java

它有两个公共方法 update(), fetch()

在实际的 update() 实现中,我调用了公共方法 fetch()

fetch() 依次调用服务。

所以现在我必须编写一个 testUpdate() 来模拟公共方法调用,即 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() 中调用的第二个公共方法

谢谢

【问题讨论】:

标签: java unit-testing junit jmockit jmock


【解决方案1】:

在我看来,您应该模拟从 Handler#fetch() 内部调用的服务类,而不是模拟 fetch() 方法。

无论如何,模拟一个类的一些方法而不模拟其他方法称为部分模拟。在 JMockit 中,您通常会为此使用 NonStrictExpectations(Object...) 构造函数,如以下示例测试中所示:

@Test
public void handlerFetchesSomethingOnUpdate()
{
    final Handler handler = new Handler();

    new NonStrictExpectations(handler) {{
        handler.fetch(); result = response;
    }};

    handler.update();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多