Mathieu Nls
Mathieu Nls

Reputation: 2365

Mockito always return null when testing dropwizard resources

I am trying to test dropwizard resources and followed http://www.dropwizard.io/manual/testing.html to do so.

However, I always get a null object from the mocked class/method.

The resource method

    @GET
    @Path("/id")
    @ApiOperation("Find property by id")
    @Produces(MediaType.APPLICATION_JSON)
    public Property findById(@QueryParam("id") int id) {

        return propertyDAO.findById(id);
    }

And the test class

public class PropertiesResourceTest {

    private static final PropertiesDAO dao = mock(PropertiesDAO.class);

    @ClassRule
    public static final ResourceTestRule resources = ResourceTestRule.builder()
            .addResource(new PropertiesResource(dao))
            .build();

    private final Property property = new Property(1);

    @Before
    public void setUp() {

        when(dao.findById(eq(1))).thenReturn(property);
        reset(dao);
    }

    @Test
    public void findById() {
        assertThat(resources.client().target("/properties/id?id=1").request().get(Property.class))
                .isEqualTo(property);
        verify(dao).findById(1);
    }

}

I tried to spin it in many ways, but the result is always the same:

expected:<Property | ID: 1 > but was:<null>

Do you have any leads on why mockito is always returning a null object ?

Upvotes: 1

Views: 1428

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95684

when(dao.findById(eq(1))).thenReturn(property);
reset(dao);

The first line stubs calls to findById. The second line, reset, immediately deletes that stubbing. You may want to swap the order of those two statements.

Though keeping mocks in static variables is a dangerous habit, and though the documentation is right to suggest you call reset manually, it is important to do so before you set expectations (i.e. as the first line in your @Before method) or after the test completes (i.e. as the last line in your @After method). Otherwise Mockito will find no stubbing there and will return its default value null.

I would recommend following their suggestion of removing the static modifier and using @Rule instead of @ClassRule. It is much less likely to inadvertently cause test pollution.

It is extremely bizarre that the documentation you linked has that code sample with the methods in that order. It should probably be updated.

Upvotes: 2

Related Questions