简体   繁体   English

使用Jmockit模拟一个公共方法

[英]Mock a public method using Jmockit

I have a class Handler.java 我有一个Handler.java类

It has 2 public methods update(), fetch() 它有2个公共方法update(),fetch()

In the actual update() implementation I make a call to the public method fetch() 在实际的update()实现中,我调用了公共方法fetch()

The fetch() in turn makes a call to a service. fetch()依次调用服务。

So now I have to write a testUpdate() which would mock the public method call ie fetch() 所以现在我必须编写一个testUpdate()来模拟公共方法调用,即fetch()

Since its not static I tried creating another instance of the Handler.java as mocked ie, 由于它不是静态的,因此我尝试创建另一个Handler.java实例作为模拟对象,例如,

private Handler handler;

@Mocked
private Handler mockedHandler;

Now using the mockedHandler, I set the below code in my testUpdate() 现在使用嘲笑的处理程序,我在testUpdate()中设置以下代码

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

handler.update();

Now, I expect the mockedhandler to be used for calling the fetch() and the handler instance for calling the update(). 现在,我希望可以使用嘲笑的处理程序来调用fetch(),并使用处理程序实例来调用update()。

But when I run the actual method call to update() is also mocked!!! 但是当我运行实际的方法时,对update()的调用也会被模拟!!!

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

Help me mock the second public method which I call inside my update() 帮我模拟在update()中调用的第二个公共方法

Thanks 谢谢

It sounds to me that you should be mocking the service class called from inside Handler#fetch() , rather than mocking the fetch() method. 在我看来,您应该模拟从Handler#fetch()内部调用的服务类,而不是模拟fetch()方法。

Anyway, mocking some methods of a class while not mocking others is called partial mocking . 无论如何,模拟类的某些方法而不模拟其他方法称为部分模拟 In JMockit, you will normally use the NonStrictExpectations(Object...) constructor for that, like in the following example test: 在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