Spring MockMvc verify body is empty

There’s a cleaner way: andExpect(jsonPath(“$”).doesNotExist()) Note that you can’t use isEmpty because it checks for an empty value, and assumes the existence of the attribute. When the attribute doesn’t exist, isEmpty throws an exception. Whereas, doesNotExist verifies that the attribute doesn’t exist, and when used with $, it checks for an empty JSON document.

How to check JSON in response body with mockMvc

I use TestNG for my unit testing. But in Spring Test Framework they both looks similar. So I believe your test be like below @Test public void testAlertFilterView() throws Exception { this.mockMvc.perform(get(“/getServerAlertFilters/v2v2v2/”). .andExpect(status().isOk()) .andExpect(content().json(“{‘data’:[{‘useRegEx’:’false’,’hosts’:’v2v2v2′}]}”)); } If you want check check json Key and value you can use jsonpath .andExpect(jsonPath(“$.yourKeyValue”, is(“WhatYouExpect”))); You might find thatcontent().json() are … Read more

How to write a unit test for a Spring Boot Controller endpoint

Spring MVC offers a standaloneSetup that supports testing relatively simple controllers, without the need of context. Build a MockMvc by registering one or more @Controller’s instances and configuring Spring MVC infrastructure programmatically. This allows full control over the instantiation and initialization of controllers, and their dependencies, similar to plain unit tests while also making it … Read more

How to count members with jsonpath?

To test size of array: jsonPath(“$”, hasSize(4)) To count members of object: jsonPath(“$.*”, hasSize(4)) I.e. to test that API returns an array of 4 items: accepted value: [1,2,3,4] mockMvc.perform(get(API_URL)) .andExpect(jsonPath(“$”, hasSize(4))); to test that API returns an object containing 2 members: accepted value: {“foo”: “oof”, “bar”: “rab”} mockMvc.perform(get(API_URL)) .andExpect(jsonPath(“$.*”, hasSize(2))); I’m using Hamcrest version 1.3 … Read more

How to check String in response body with mockMvc

You can call andReturn() and use the returned MvcResult object to get the content as a String. See below: MvcResult result = mockMvc.perform(post(“/api/users”).header(“Authorization”, base64ForTestUser).contentType(MediaType.APPLICATION_JSON) .content(“{\”userName\”:\”testUserDetails\”,\”firstName\”:\”xxx\”,\”lastName\”:\”xxx\”,\”password\”:\”xxx\”}”)) .andDo(MockMvcResultHandlers.print()) .andExpect(status().isBadRequest()) .andReturn(); String content = result.getResponse().getContentAsString(); // do what you will