java - MockMvcResultMatchers - jsonPath() vs content()
问题描述
I'm testing Spring REST controllers using org.springframework.test.web.servlet.MockMvc
object.
I can verify response JSON using MockMvcResultMatchers.content()
method or MockMvcResultMatchers.jsonPath()
method which accepts Hamcrest matcher. I'm wondering which approach is better and what are the best practices? With complicated structure Hamcrest matchers seems really hard to read, and with content()
, long JSON has to be externalized to separate file (but it's not big deal IMHO). Should I prefer one option to another or it's completely personal thing?
解决方案
content()
当您的响应不是 JSON 时,您可以使用。即,如果响应是纯文本。
jsonPath()
为您提供更多检查响应的机会。例如
你只需要检查一个特定的领域;
你需要检查json-array,但你不关心排序;
您比较更大/更少,但不完全匹配,
推荐阅读
- mysql - 在 MySQL 上将值拆分为多行
- spring-cloud - 如何在 Feign 中使用 http2 以获得更好的 RPC 性能?
- excel - 如何为 Excel 创建满足特定要求的唯一 ID
- spring - 发生错误时如何不使用 JMS 消息
- angular - 在 tomcat 上部署 Angular 6 应用程序
- machine-learning - 迁移学习完全不同的领域和任务
- systemd - 触发 systemd OnFailure 时如何获取进程的退出代码?
- marklogic - 如何从应用程序服务器运行 mlcp 导入林
- java - Java 存在于系统上但未安装。这是网络安全问题吗?
- java - 使用 FileInputStream 和 outstream 生成损坏的文件:java、android