Using Mockito to mock some methods but not others

mockito
mockito

In this post I am going to show you how to create partial mocks using Mockito.
Partial mocks are useful when you only need to mock some methods of an object leaving the remainder free to respond to calls normally (i.e. as implemented).

I often reach out for partial mocks when I am writing tests for a method which in turn invoke other methods in the same class and these methods are difficult to set up because they use a bunch of class variables.

Look at the class below.


class OrderItem {
    private Product product;
    private Integer quantity;
    private Money unitPrice;
    ...
    ...

    public Money price() {
        Money price = unitPrice.multiple(quantity);
        auditOperation();
    }
    public void auditOperation() {
        // Logic involves setting up a lot of state. i.e class variables
    }
}

Assume I want to test the price() method and am not too concerned with the auditOperation() logic. I would like to test the implementation for the price() method while mocking out the implementation for the auditOperation() method. This is when I reach out for partial mocks because they let me mock out the auditOpertion() method while still letting me test the price() method.

Warning: partial mocks should be used with caution. They are pointing at a smell in your design.

With Mockito you can achieve partial mocks using either mock() or spy()

With mock() methods are mocked by default and real implementation is used only if it is explicitly coded to do so.

List mockList = mock(LinkedList.class);

//by default, calling the methods of mock object will do nothing
mockList.add(10);

//mock object will call the real method
when(mockList.add(10)).thenCallRealMethod();

Conversely with the spy() real implementation is invoked by default and mocked responses need to be explicitly coded.

List spyList = spy(list);

//spy object will call the real method
spyList.add(10);

//spy object will return mocked response
when(spyList.add(10)).thenReturn(true);

This rounds up our discussion on how to create partial mocks using Mockito.
If you found this useful don’t forget to share it 🙂