2017-11-09 1 views
2

서블릿 끝점의 응답을 확인하는 간단한 junit 테스트가 있습니다.MockMvc junit 테스트에서 @RestController의 ResponseBody를 객체로 얻는 방법은 무엇입니까?

문제점 : 문자열/json/xml 표현이 아닌 java 객체Person과 같은 응답을 얻고 싶습니다.

그럴 수 있습니까?

@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? 
    } 
} 

답변

3

이 같은 직렬화 수 : 당신이 내 목표로 mockMvc

+0

직접적인 접근 방법이 없다면 좋은 해결책입니다. – membersound

+0

또한 응답 객체 JSON을'.andExpect (content(). json ("{ 'message': ok '}")); 등으로 직접 확인할 수 있습니다. –

0

당신은 TestRestTemplate::getForEntity를 사용할 수 @Autowire 수 있습니다 주로 전체 설정을 테스트하는 것이 었습니다. 자동 설정 된 objectmapper 및 restcontroller 집합을 사용하여 방금 엔드 포인에 대한 모의 작업을 만들었습니다. int. 그리고 거기에 응답으로 입력 매개 변수가 반환되었으므로 유효성을 검사 할 수 있습니다.

@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(); 
    } 
} 
0

로 제한하지 않는 경우

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

당신은 또한 ObjectMapper

관련 문제