使用JSONPath的MockMVC无法读取

时间:2018-09-02 05:10:05

标签: java jsonpath spring-boot-test mockmvc

此测试用例已修复,我无法对其进行修改。在控制器中,我返回了出现在输出的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();
        }


    }
}

但是,我无法检索数据“ section”和“ title”。如何通过这个测试用例。应该在哪里设置输出数据以便能够在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 = []

我需要提取

1 个答案:

答案 0 :(得分:0)

javadoc

  

静态JsonPathResultMatchers jsonPath(字符串表达式,对象... 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。