Search code examples
junitmockitojmockit

Convert from JMockit to Mockito framework


I have seen a few examples of people switching from Mockito to JMockit, but I am doing the opposite. I am not really sure what to do with the @Mocked parameters. Do these just become @Mock instance variables? I think the NonStrictExpectations clause should become "when" clauses like:

when(rpManager.login()).thenReturn(true);

and the Verifications section becomes "verify" clauses.

This is an example of a full test case I am converting.

@Test
public void testGetOffersUnsuccessfulResponse(@Mocked final RPRequest mockRequest, @Mocked final RPResponse mockResponse) {

    final String sessionId = "123";

    new NonStrictExpectations() {{
        rpManager.login(); returns(true);
        rpManager.newRequest(anyString); returns(mockRequest);
        mockRequest.sendRequest(); returns(mockResponse);
        mockResponse.isSuccess(); returns(false);
    }};

    final EpiphanyConnection connection = new EpiphanyConnection(getDummyConnectionProperties(), getDummyActionMapping());
    assertTrue(connection.connect());

    final InteractionContext interactionContext = new InteractionContext();
    interactionContext.setRequestContext(new RequestContext());
    interactionContext.getRequestContext().setAction(getDummyActionMapping().keySet().iterator().next());

    interactionContext.setUserContext(new UserContext());
    interactionContext.getUserContext().setSessionId(sessionId);

    final OfferTranslator offerTranslator = connection.fetchCommunications(interactionContext);
    assertNotNull(offerTranslator);

    new Verifications() {{

        // failure in the below likely indicates mismatched JSON string.
        mockRequest.setData("SessionId", sessionId);
        mockRequest.sendRequest(); times=1;
    }};
}

Solution

  • Mockito, you are correct there, does not expect any when clause to be actually needed. Like the name implies, WHEN this and that happens, then do something - if it did not happen, then that's ok as well.

    To make sure that something has actually been called, use verify.

    @Mock will create a mocked instance, correct:

    @Mock
    private MyService service; // will result in a mocked "MyService" instance
    

    Don't forget to either call MockitoAnnotations.initMock(this); or to use @RunWith(MockitoJUnitRunner.class) to make sure the annotations are actually used.