Spring MockMvc验证体是空的

isA*_*Don 11 spring spring-test spring-test-mvc

我有一个简单的Spring测试

@Test
public void getAllUsers_AsPublic() throws Exception {
    doGet("/api/users").andExpect(status().isForbidden());
}

public ResultActions doGet(String url) throws Exception {
    return mockMvc.perform(get(url).header(header[0],header[1])).andDo(print());
}
Run Code Online (Sandbox Code Playgroud)

我想验证响应正文是否为空.例如做类似的事情.andExpect(content().isEmpty())

Abh*_*kar 18

有一个更清洁的方式:

andExpect(jsonPath("$").doesNotExist())
Run Code Online (Sandbox Code Playgroud)

请注意,您无法使用,isEmpty因为它检查空值,并假定存在属性.当该属性不存在时,isEmpty抛出异常.然而,doesNotExist验证该属性不存在,并且在使用时$,它检查空JSON文档.

  • 需要注意的是,当内容主体存在并包含字符串“null”(不带引号)时,“andExpect(jsonPath("$").doesNotExist())”将默默地成功,这可能是也可能不是您想要的。我在2.4.0版本上测试过这个。 (2认同)

Dav*_*ave 5

我认为这些选项之一应该可以满足您的需求,尽管效果不如isEmpty()(来自ContentResultMatchers文档):

.andExpect(content().bytes(new Byte[0])
Run Code Online (Sandbox Code Playgroud)

要么

.andExpect(content().string(""))
Run Code Online (Sandbox Code Playgroud)

  • 你是对的@DaveyDaveDave,谢谢你。有趣的是我错过了。在这种情况下,对 `jsonPath("$").doesNotExist()` 的期望不会失败这一事实是一个问题。 (2认同)