简体   繁体   English

如何在MockMvc junit测试中将@RestController的ResponseBody作为对象?

[英]How to get ResponseBody of @RestController as object in a MockMvc junit test?

I have a simple junit test that verifies the response of a servlet endpoint. 我有一个简单的junit测试,用于验证servlet端点的响应。

Problem: I want to obtain the response as java object Person , and not as string/json/xml representation. 问题:我想获得作为java对象 Person的响应,而不是作为string / json / xml表示。

Is that possible? 那可能吗?

@RestController
public class PersonController {
    @GetMapping("/person")
    public PersonRsp getPerson(int id) {
        //...
        return rsp;
    }   
}

@RunWith(SpringRunner.class)
@WebMvcTest(value = PersonController.class)
public class PersonControllerTest {
    @Autowired
    private MockMvc mvc;

    @Test
    public void test() {
        MvcResult rt = mvc.perform(get("/person")
                .param("id", "123")
                .andExpect(status().isOk())
                .andReturn();

        //TODO how to cast the result to (Person) p?
    }
}

you could deserialize it like this: 你可以像这样反序列化它:

String json = rt.getResponse().getContentAsString();
Person person = new ObjectMapper().readValue(json, Person.class);

You can also @Autowire the ObjectMapper 你也可以@Autowire ObjectMapper

As my goal was mainly to test the whole setup, means by spring autoconfigured set of objectmapper and restcontroller, I just created a mock for the endpoint. 由于我的目标主要是测试整个设置,意味着通过spring自动配置的objectmapper和restcontroller集合,我只是为端点创建了一个模拟。 And there returned the input parameter as response, so I can validate it: 并返回输入参数作为响应,所以我可以验证它:

@RestController
public class PersonControllerMock {
    @GetMapping("/person")
    public PersonDTO getPerson(PersonDTO dto) {
        return dto;
    }   
}


@RunWith(SpringRunner.class)
@WebMvcTest(value = PersonControllerMock.class)
public class PersonControllerTest {
    @Autowired
    private MockMvc mvc;

    @Test
    public void test() {
        mvc.perform(get("/person")
                .param("id", "123")
                .param("firstname", "john")
                .param("lastname", "doe")
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.firstname").value("john"))
                .andExpect(jsonPath("$.lastname").value("doe"))
                .andReturn();
    }
}

如果不受mockMvc限制,可以使用TestRestTemplate::getForEntity mockMvc

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM