繁体   English   中英

如何使用 mockMvc 检查响应正文中的字符串

[英]How to check String in response body with mockMvc

我有简单的集成测试

@Test
public void shouldReturnErrorMessageToAdminWhenCreatingUserWithUsedUserName() throws Exception {
    mockMvc.perform(post("/api/users").header("Authorization", base64ForTestUser).contentType(MediaType.APPLICATION_JSON)
        .content("{\"userName\":\"testUserDetails\",\"firstName\":\"xxx\",\"lastName\":\"xxx\",\"password\":\"xxx\"}"))
        .andDo(print())
        .andExpect(status().isBadRequest())
        .andExpect(?);
}

在最后一行中,我想将响应正文中收到的字符串与预期的字符串进行比较

作为回应,我得到:

MockHttpServletResponse:
          Status = 400
   Error message = null
         Headers = {Content-Type=[application/json]}
    Content type = application/json
            Body = "Username already taken"
   Forwarded URL = null
  Redirected URL = null

用 content(), body() 尝试了一些技巧,但没有任何效果。

您可以调用andReturn()并使用返回的MvcResult对象将内容作为String获取。

见下文:

MvcResult result = mockMvc.perform(post("/api/users").header("Authorization", base64ForTestUser).contentType(MediaType.APPLICATION_JSON)
            .content("{\"userName\":\"testUserDetails\",\"firstName\":\"xxx\",\"lastName\":\"xxx\",\"password\":\"xxx\"}"))
            .andDo(MockMvcResultHandlers.print())
            .andExpect(status().isBadRequest())
            .andReturn();

String content = result.getResponse().getContentAsString();
// do what you will 

@Sotirios Delimanolis 回答完成了这项工作,但是我正在寻找比较这个 mockMvc 断言中的字符串

所以这里

.andExpect(content().string("\"Username already taken - please try with different username\""));

当然我的断言失败了:

java.lang.AssertionError: Response content expected:
<"Username already taken - please try with different username"> but was:<"Something gone wrong">

因为:

  MockHttpServletResponse:
            Body = "Something gone wrong"

所以这证明它有效!

Spring MockMvc 现在直接支持 JSON。 所以你只说:

.andExpect(content().json("{'message':'ok'}"));

与字符串比较不同,它会说“缺少字段 xyz”或“消息预期 'ok' 得到 'nok'。

此方法是在 Spring 4.1 中引入的。

阅读这些答案,我可以看到很多与 Spring 4.x 版有关的内容,出于各种原因,我正在使用 3.2.0 版。 所以像 json 这样的东西直接从content()支持是不可能的。

我发现使用MockMvcResultMatchers.jsonPath真的很简单而且很有效。 这是一个测试 post 方法的示例。

此解决方案的好处是您仍在匹配属性,而不是依赖完整的 json 字符串比较。

(使用org.springframework.test.web.servlet.result.MockMvcResultMatchers

String expectedData = "some value";
mockMvc.perform(post("/endPoint")
                .contentType(MediaType.APPLICATION_JSON)
                .content(mockRequestBodyAsString.getBytes()))
                .andExpect(status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.data").value(expectedData));

请求正文只是一个 json 字符串,如果需要,您可以轻松地从真正的 json 模拟数据文件中加载它,但我没有在此处包含它,因为它会偏离问题。

返回的实际 json 如下所示:

{
    "data":"some value"
}

取自spring的教程

mockMvc.perform(get("/" + userName + "/bookmarks/" 
    + this.bookmarkList.get(0).getId()))
    .andExpect(status().isOk())
    .andExpect(content().contentType(contentType))
    .andExpect(jsonPath("$.id", is(this.bookmarkList.get(0).getId().intValue())))
    .andExpect(jsonPath("$.uri", is("http://bookmark.com/1/" + userName)))
    .andExpect(jsonPath("$.description", is("A description")));

isimport static org.hamcrest.Matchers.*;

jsonPath可从import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;

jsonPath参考可以在这里找到

Spring security 的@WithMockUser和 hamcrest 的containsString匹配器提供了一个简单而优雅的解决方案:

@Test
@WithMockUser(roles = "USER")
public void loginWithRoleUserThenExpectUserSpecificContent() throws Exception {
    mockMvc.perform(get("/index"))
            .andExpect(status().isOk())
            .andExpect(content().string(containsString("This content is only shown to users.")));
}

更多示例在 github

一种可能的方法是简单地包含gson依赖项:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>

并解析值以进行验证:

@RunWith(SpringRunner.class)
@WebMvcTest(HelloController.class)
public class HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private HelloService helloService;

    @Before
    public void before() {
        Mockito.when(helloService.message()).thenReturn("hello world!");
    }

    @Test
    public void testMessage() throws Exception {
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/"))
                .andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON_VALUE))
                .andReturn();

        String responseBody = mvcResult.getResponse().getContentAsString();
        ResponseDto responseDto
                = new Gson().fromJson(responseBody, ResponseDto.class);
        Assertions.assertThat(responseDto.message).isEqualTo("hello world!");
    }
}

这里有更优雅的方式

mockMvc.perform(post("/retrieve?page=1&countReg=999999")
            .header("Authorization", "Bearer " + validToken))
            .andExpect(status().isOk())
            .andExpect(content().string(containsString("regCount")));

这是一个如何解析 JSON 响应,甚至如何使用 JSON 形式的 bean 发送请求的示例:

  @Autowired
  protected MockMvc mvc;

  private static final ObjectMapper MAPPER = new ObjectMapper()
    .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
    .registerModule(new JavaTimeModule());

  public static String requestBody(Object request) {
    try {
      return MAPPER.writeValueAsString(request);
    } catch (JsonProcessingException e) {
      throw new RuntimeException(e);
    }
  }

  public static <T> T parseResponse(MvcResult result, Class<T> responseClass) {
    try {
      String contentAsString = result.getResponse().getContentAsString();
      return MAPPER.readValue(contentAsString, responseClass);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  @Test
  public void testUpdate() {
    Book book = new Book();
    book.setTitle("1984");
    book.setAuthor("Orwell");
    MvcResult requestResult = mvc.perform(post("http://example.com/book/")
      .contentType(MediaType.APPLICATION_JSON)
      .content(requestBody(book)))
      .andExpect(status().isOk())
      .andReturn();
    UpdateBookResponse updateBookResponse = parseResponse(requestResult, UpdateBookResponse.class);
    assertEquals("1984", updateBookResponse.getTitle());
    assertEquals("Orwell", updateBookResponse.getAuthor());
  }

正如您在此处看到的, Book是一个请求 DTO,而UpdateBookResponse是一个从 JSON 解析的响应对象。 您可能想要更改 Jackson 的ObjectMapper配置。

另一种选择是:

when:

def response = mockMvc.perform(
            get('/path/to/api')
            .header("Content-Type", "application/json"))

then:

response.andExpect(status().isOk())
response.andReturn().getResponse().getContentAsString() == "what you expect"

您可以使用getContentAsString方法将响应数据作为字符串获取。

    String payload = "....";
    String apiToTest = "....";
    
    MvcResult mvcResult = mockMvc.
                perform(post(apiToTest).
                content(payload).
                contentType(MediaType.APPLICATION_JSON)).
                andReturn();
    
    String responseData = mvcResult.getResponse().getContentAsString();

您可以参考此链接进行测试应用程序。

String body = mockMvc.perform(bla... bla).andReturn().getResolvedException().getMessage()

这应该为您提供响应的主体。 在您的情况下,“用户名已被占用”。

另一个例子是:

.andExpect(jsonPath("$").value(containsString("You have successfully deleted")));

身体反应:

Body = You have successfully deleted a [Object] with ID: 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM