首页 > 解决方案 > 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?

标签: javajsonspringspring-restcontrollermockmvc

解决方案


content()当您的响应不是 JSON 时,您可以使用。即,如果响应是纯文本。

jsonPath()为您提供更多检查响应的机会。例如

  • 你只需要检查一个特定的领域;

  • 你需要检查json-array,但你不关心排序;

  • 您比较更大/更少,但不完全匹配,


推荐阅读