【问题标题】:Mockito always return null when testing dropwizard resources测试 dropwizard 资源时,Mockito 总是返回 null
【发布时间】:2015-07-10 15:07:51
【问题描述】:

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

但是,我总是从模拟的类/方法中得到一个空对象。

资源方法

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

        return propertyDAO.findById(id);
    }

还有测试类

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 总是返回一个空对象有任何线索吗?

【问题讨论】:

    标签: unit-testing junit mockito dropwizard


    【解决方案1】:
    when(dao.findById(eq(1))).thenReturn(property);
    reset(dao);
    

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

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

    我建议按照他们的建议删除static 修饰符并使用@Rule 而不是@ClassRule。无意中造成测试污染的可能性要小得多。

    非常奇怪的是,您链接的文档中有该代码示例以及该顺序的方法。应该会更新吧。

    【讨论】:

    • 好吧,我觉得按照文档来信是愚蠢的......无论如何,它有效。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    相关资源
    最近更新 更多