This test case is fixed and I cannot modify it. In the controller I am returning News Object which is appearing in the Model component of the output. But the JSONPath is unable to find it.
If this test case needs to be passed, where should my output appear or what should I return from the controller.
@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();
}
}
}
But, I am unable to retrieve the data "section" and "title". How to pass this testcase. Where should the output data be set to be able to see it in jsonpath.
This is my mock when I print it to console
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 = []
I need to extract
From the javadoc
static JsonPathResultMatchers jsonPath(String expression, Object... args)
Access to response body assertions using a JsonPath expression to inspect a specific subset of the body.
And from your output
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Language=[en]}
Content type = null
Body =
Forwarded URL = api/news/topstories Redirected URL = null
Cookies = []
It seems you have an empty response body.
Please modify your controller to produce the proper json in the response body.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.