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

How to check String in response body with mockMvc(如何使用 mockMvc 检查响应正文中的字符串)
本文介绍了如何使用 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(?);
}

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

In last line I want to compare string received in response body to expected string

作为回应,我得到:

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() 尝试了一些技巧,但没有任何效果.

Tried some tricks with content(), body() but nothing worked.

推荐答案

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

@Sotirios Delimanolis answer do the job however I was looking for comparing strings within this mockMvc assertion

原来是这样

.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"

所以这证明它有效!

这篇关于如何使用 mockMvc 检查响应正文中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Show progress during FTP file upload in a java applet(在 Java 小程序中显示 FTP 文件上传期间的进度)
How to copy a file on the FTP server to a directory on the same server in Java?(java - 如何将FTP服务器上的文件复制到Java中同一服务器上的目录?)
FTP zip upload is corrupted sometimes(FTP zip 上传有时会损坏)
Enable logging in Apache Commons Net for FTP protocol(在 Apache Commons Net 中为 FTP 协议启用日志记录)
Checking file existence on FTP server(检查 FTP 服务器上的文件是否存在)
FtpClient storeFile always return False(FtpClient storeFile 总是返回 False)