Mockito 在测试 dropwizard 资源时总是 return null

Mockito always return null when testing dropwizard resources

我正在尝试测试 dropwizard 资源并按照 http://www.dropwizard.io/manual/testing.html 进行测试。

但是,我总是从模拟的 class/method 中得到一个空对象。

资源方法

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

        return propertyDAO.findById(id);
    }

和测试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);
    }

}

我尝试了很多方法来旋转它,但结果总是一样的:

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

关于为什么 mockito 总是返回空对象,您有什么线索吗?

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

第一行存根调用 findById。第二行,resetimmediately deletes that stubbing您可能想交换这两个语句的顺序。

尽管将模拟保存在静态变量中是一个危险的习惯,尽管文档建议您手动调用 reset 是正确的,但在设置期望值之前 这样做很重要(即作为@Before 方法中的第一行)或测试完成后(即作为@After 方法中的最后一行)。否则 Mockito 会发现那里没有存根并将 return 其默认值 null.

我建议按照他们的建议删除 static 修饰符并使用 @Rule 而不是 @ClassRule。更不容易无意中造成测试污染。

非常奇怪的是,您链接的文档中包含该代码示例以及该顺序的方法。它可能应该更新。