简体   繁体   English

如何使用 mockMvc 检查响应正文中的 JSON

[英]How to check JSON in response body with mockMvc

This is my method inside my controller which is annotated by @Controller这是我的控制器中的方法,由@Controller注释

@RequestMapping(value = "/getServerAlertFilters/{serverName}/", produces = "application/json; charset=utf-8")
    @ResponseBody
    public JSONObject getServerAlertFilters(@PathVariable String serverName) {
        JSONObject json = new JSONObject();
        List<FilterVO> filteredAlerts = alertFilterService.getAlertFilters(serverName, "");
        JSONArray jsonArray = new JSONArray();
        jsonArray.addAll(filteredAlerts);
        json.put(SelfServiceConstants.DATA, jsonArray);
        return json;
    }

I am expecting {"data":[{"useRegEx":"false","hosts":"v2v2v2"}]} as my json.我期待{"data":[{"useRegEx":"false","hosts":"v2v2v2"}]}作为我的 json。

And this is my JUnit test:这是我的 JUnit 测试:

@Test
    public final void testAlertFilterView() {       
        try {           
            MvcResult result = this.mockMvc.perform(get("/getServerAlertFilters/v2v2v2/").session(session)
                    .accept("application/json"))
                    .andDo(print()).andReturn();
            String content = result.getResponse().getContentAsString();
            LOG.info(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Here is the console output:这是控制台输出:

MockHttpServletResponse:
              Status = 406
       Error message = null
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = null
      Redirected URL = null
             Cookies = []

Even result.getResponse().getContentAsString() is an empty string.甚至result.getResponse().getContentAsString()也是一个空字符串。

Can someone please suggest how to get my JSON in my JUnit test method so that I can complete my test case.有人可以建议如何在我的 JUnit 测试方法中获取我的 JSON,以便我可以完成我的测试用例。

I use TestNG for my unit testing.我使用 TestNG 进行单元测试。 But in Spring Test Framework they both looks similar.但是在 Spring Test Framework 中,它们看起来很相似。 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")));如果你想检查 json 键和值,你可以使用 jsonpath .andExpect(jsonPath("$.yourKeyValue", is("WhatYouExpect")));

You might find that content().json() are not solveble please add您可能会发现content().json()无法解决,请添加

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

The 406 Not Acceptable status code means that Spring couldn't convert the object to json. 406 Not Acceptable状态码意味着 Spring 无法将对象转换为 json。 You can either make your controller method return a String and do return json.toString();你可以让你的控制器方法返回一个字符串并return json.toString(); or configure your own HandlerMethodReturnValueHandler .或配置您自己的HandlerMethodReturnValueHandler Check this similar question Returning JsonObject using @ResponseBody in SpringMVC检查这个类似的问题Returning JsonObject using @ResponseBody in SpringMVC

You can try the below for get and post methods您可以尝试以下获取和发布方法

@Autowired
private MuffinRepository muffinRepository;

@Test
public void testGetMethod throws Exception(){
    Muffin muffin = new Muffin("Butterscotch");
    muffin.setId(1L);
    
    BddMockito.given(muffinRepository.findOne(1L)).
        willReturn(muffin);
        
    mockMvc.perform(MockMvcRequestBuilders.
        get("/muffins/1")).
        andExpect(MockMvcResutMatchers.status().isOk()).
        andExpect(MockMvcResutMatchers.content().string("{\"id\":1, "flavor":"Butterscotch"}"));    
}

//Test to do post operation
@Test
public void testPostMethod throws Exception(){
    Muffin muffin = new Muffin("Butterscotch");
    muffin.setId(1L);
    
    BddMockito.given(muffinRepository.findOne(1L)).
        willReturn(muffin);
        
    mockMvc.perform(MockMvcRequestBuilders.
        post("/muffins")
        .content(convertObjectToJsonString(muffin))
        .contentType(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(MockMvcResutMatchers.status().isCreated())
        .andExpect(MockMvcResutMatchers.content().json(convertObjectToJsonString(muffin))); 
}

If the response is empty then make sure to override equals() and hashCode() methods on the Entity your repository is working with:如果响应为空,请确保覆盖存储库正在使用的Entity上的equals()hashCode()方法:

//Converts Object to Json String
private String convertObjectToJsonString(Muffin muffin) throws JsonProcessingException{
    ObjectWriter writer = new ObjectWriter().writer().withDefaultPrettyPrinter();
    return writer.writeValueAsString(muffin);
}

There are 2 ways to check JSON responses.有两种方法可以检查 JSON 响应。 Lemme guide you through both of them, (taking test method from the question above, and assuming response {"data":[{"useRegEx":"false","hosts":"v2v2v2"}]} as given above)让我引导您完成这两个,(从上面的问题中采用测试方法,并假设响应{"data":[{"useRegEx":"false","hosts":"v2v2v2"}]}如上所述)

Method 1) Asserting complete JSON方法 1) 断言完整的 JSON

@Test
public final void testAlertFilterView() {       
    mockMvc.perform(get("/getServerAlertFilters/v2v2v2/")
           .contentType("application/json"))
           .andExpect(status().isOk())
           // you may even read bigger json responses from file and convert it to string, instead of simply hardcoding it in test class
           .andExpect(content().json("{"data":[{"useRegEx":"false","hosts":"v2v2v2"}]}"))     
}

Method 2) Asserting specific key-value of response (not writing redundant piece of code)方法2)断言响应的特定键值(不编写冗余代码)

.andExpect(jsonPath("$.data[0].useRegEx").value(false))
.andExpect(jsonPath("$.data[0].hosts").value("v2v2v2"));

Another thing you might need is the import statement,您可能需要的另一件事是导入语句,

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

If you want to check a few values in a specific field of JSON如果要检查 JSON 特定字段中的一些值

.andExpect(MockMvcResultMatchers.jsonPath("$.message",
    AllOf.allOf(
        StringContains.containsString("name: must not be null"),
        StringContains.containsString("type: must not be null")
    )));

How it looks in the test class.它在测试类中的外观。 JUnit4. JUnit4。

import com.fasterxml.jackson.databind.ObjectMapper;
import org.hamcrest.core.AllOf;
import org.hamcrest.core.StringContains;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

@RunWith(MockitoJUnitRunner.class)
public class YourControllerTest {

  @Mock
  private YourService service;

  private MockMvc mvc;

  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);
    mvc = MockMvcBuilders
        .standaloneSetup(new YourController(service))
        .setControllerAdvice(new YourExceptionHandler())
        .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
        .build();
  }

  @Test
  public void yourControllerMethodName_400_validation() throws Exception {
    String path = "/orders/{orderId}/items";
    Integer orderId = 123;

    YourRequestDto requestDto = YourTestFactory.buildYourRequestDto();
    requestDto.setName(null);
    requestDto.setType(null);

    YourResponseDto expected = YourTestFactory.buildYourResponseDto(requestDto);

    Mockito
        .when(service.someMethod(orderId, requestDto))
        .thenReturn(expected);

    mvc
        .perform(
            MockMvcRequestBuilders.post(path, orderId)
                .contentType(MediaType.APPLICATION_JSON)
                .content(new ObjectMapper().writeValueAsString(requestDto))
        )
        .andExpect(MockMvcResultMatchers.status().isBadRequest())
        .andExpect(MockMvcResultMatchers.jsonPath("$.message",
            AllOf.allOf(
                StringContains.containsString("name: must not be null"),
                StringContains.containsString("type: must not be null")
            )));
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 mockMvc 检查响应正文中的字符串 - How to check String in response body with mockMvc 如何使用 mockMvc 检查响应正文中的值 - AssertionError: Status expected:&lt;201&gt; but was:&lt;400&gt; - How to check values in response body with mockMvc - AssertionError: Status expected:<201> but was:<400> 如何使用MockMvc在响应主体中格式化Spring REST Docs - How to format Spring REST Docs in response body with mockMvc 如何使用 Java 检查 JSON 响应是否返回 [] 或带有正文的响应? - How to check if JSON respone returns [ ] or response with body using Java? 使用Spring MockMVC时如何从JSON响应中提取值 - How to extract value from JSON response when using Spring MockMVC MockMVC JsonPath 响应有空体? - MockMVC JsonPath response has empty body? 如何将文件和正文添加到 MockMvc? - How to add a file and body to MockMvc? 使用 MockMvc.jsonpath() 方法测试 API 响应正文时如何在括号 [] 内输入 - How to enter inside a bracket [] when testing API response body using MockMvc .jsonpath() method 如何检查响应正文是否有数据? - How to check if response body has data? 如何断言响应字符串主体是 JSON 格式? - How to assert that response String body is in JSON format?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM