![](/img/trans.png)
[英]How to enter inside a bracket [] when testing API response body using MockMvc .jsonpath() method
[英]MockMVC using JSONPath unable to read
这个测试用例是固定的,我无法修改。 在控制器中,我返回了出现在输出的Model组件中的News Object。 但是JSONPath无法找到它。
如果需要通过此测试用例,则应该在哪里显示我的输出,或者应该从控制器返回什么。
@SpringBootTest
@RunWith(SpringRunner.class)
public class NewsControllerTest {
private MockMvc mockMvc;
@Autowired
WebApplicationContext context;
@InjectMocks
private NewsController newsController;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void retrievetest_ok() throws Exception {
try {
mockMvc.perform(get("/api/news/topstories" )).andDo(print())
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.title").exists())
.andExpect(MockMvcResultMatchers.jsonPath("$.section").exists());
}catch(Exception e) {
e.printStackTrace();
}
}
}
但是,我无法检索数据“部分”和“标题”。 如何通过这个测试用例。 应该将输出数据设置在哪里,以便能够在jsonpath中看到它。
当我将其打印到控制台时,这是我的模拟
MockHttpServletRequest:
HTTP Method = GET
Request URI = /api/news/topstories
Parameters = {}
Headers = {}
Body = <no character encoding set>
Session Attrs = {}
Handler:
Type = com.example.project.NewsController
Method = public java.util.Map<java.lang.String, java.lang.String> com.example.project.NewsController.getNews()
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = api/news/topstories
View = null
Attribute = section
value = U.S.
Attribute = title
value = 4 Takeaways from Tuesday’s Primaries
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Language=[en]}
Content type = null
Body =
Forwarded URL = api/news/topstories
Redirected URL = null
Cookies = []
我需要提取
静态JsonPathResultMatchers jsonPath(String expression,Object ... args)
使用JsonPath表达式访问响应主体断言以检查主体的特定子集。
从你的输出
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Language=[en]}
Content type = null
Body =
Forwarded URL = api/news/topstories Redirected URL = null
Cookies = []
似乎您的响应正文为空。
请修改您的控制器以在响应主体中生成正确的json。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.