Thursday, December 02, 2010

Mockito: Two simple ways to create mock

Mockito is the simplest, cleanest and easiest to start with among other mocking frameworks present in java world. Being so simple, it still tries to make our test more cleaner and readable by providing two simple ways to create mocks depending upon the need. Let's look into those.

1. Using static mock method

Socket socketMock = mock(Socket.class);

This is most common way to create mock. But what if mock is to be created and used in each test method in test class? One way to do is declare it as field and initialize it before test method is called. Something like this:

public class RequestProcessorTest {
    private Socket socketMock;

    @Before public void init() {
        socketMock = mock(Socket.class);
    }
}

This looks simple and clean, but what if there are more than one field to be mocked? Create mock for each in init(). It's simple. But is there more simpler way to combine declaration and initialization process? Yes! that takes us to second point.

2. Using @Mock annotation

@Mock annotation is shorthand for creating mock. This code shows how to create mocks using annotation.

public class RequestProcessorTest {
    @Mock private Socket socketMock;

    @Before public void initMock() {
        MockitoAnnotations.initMocks(this);
    }
}

MockitoAnnotations.initMocks() is important here. It initializes all fields with @Mock annotation. In above code it creates mock of Socket and assigns it to socketMock. Using @Mock annotation has below listed advantages( as specified in mockito java docs):

  • Minimizes repetitive mock creation code.
  • Makes the test class more readable.
  • Makes the verification error easier to read because the field name is used to identify the mock.

So when to use #1 and #2? As listed in java docs of @Mock annotation, if mock creation code is repetitive, I prefer to use #2 otherwise #1.

No comments:

Post a Comment