使用JSONPath的MockMVC无法读取

问题描述 投票:0回答:1

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

我需要提取

java jsonpath spring-boot-test mockmvc
1个回答
0
投票

来自javadoc

static 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。

© www.soinside.com 2019 - 2024. All rights reserved.