Search code examples
javaunit-testingjunitjmockitjmock

Mock a public method using Jmockit


I have a class Handler.java

It has 2 public methods update(), fetch()

In the actual update() implementation I make a call to the public method fetch()

The fetch() in turn makes a call to a service.

So now I have to write a testUpdate() which would mock the public method call i.e. fetch()

Since its not static I tried creating another instance of the Handler.java as mocked i.e,

private Handler handler;

@Mocked
private Handler mockedHandler;

Now using the mockedHandler, I set the below code in my 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().

But when I run the actual method call to update() is also mocked!!!

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()

Thanks


Solution

  • It sounds to me that you should be mocking the service class called from inside Handler#fetch(), rather than mocking the fetch() method.

    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:

    @Test
    public void handlerFetchesSomethingOnUpdate()
    {
        final Handler handler = new Handler();
    
        new NonStrictExpectations(handler) {{
            handler.fetch(); result = response;
        }};
    
        handler.update();
    }