繁体   English   中英

使用Jmockit模拟一个公共方法

[英]Mock a public method using Jmockit

我有一个Handler.java类

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

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

fetch()依次调用服务。

所以现在我必须编写一个testUpdate()来模拟公共方法调用,即fetch()

由于它不是静态的,因此我尝试创建另一个Handler.java实例作为模拟对象,例如,

private Handler handler;

@Mocked
private Handler mockedHandler;

现在使用嘲笑的处理程序,我在testUpdate()中设置以下代码

new NonStrictExpectations(){
mockedHandler.fetch();
returns(response);
};

handler.update();

现在,我希望可以使用嘲笑的处理程序来调用fetch(),并使用处理程序实例来调用update()。

但是当我运行实际的方法时,对update()的调用也会被模拟!!!

i.e. handler.update(); is not at all going to the update().

帮我模拟在update()中调用的第二个公共方法

谢谢

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

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

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

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

    handler.update();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM