SpringFramework/JUnit Test

Mock Response 객체로 변환

lovineff 2020. 11. 26. 18:12

Mock 객체를 이용해 Controller를 호출하고, 그 결과를 객체로 변환하여 테스트한다.

@SpringBootTest
@AutoConfigureMockMvc
class TestControllerTest {
    final static String head_url = "/test";

    @Autowired
    CleanAPIController cleanAPIController;

    @Autowired
    MockMvc mockMvc;

    @Test
    void bbsList() throws Exception {
    	// 기본 응답 테스트
        mockMvc.perform(get(head_url + "/bbs/list"))
                .andExpect(status().isOk())
                .andDo(print());
		
        // 변환 테스트
        MockHttpServletResponse response = mockMvc.perform(get(head_url + "/bbs/list"))
                .andExpect(status().isOk())
                .andReturn()
                .getResponse();

        // mock 객체 변환
        ObjectMapper objectMapper = new ObjectMapper();
        BbsResult bbsResult = objectMapper.readValue(response.getContentAsString(), BbsResult.class);
        assertEquals(200, bbsResult.getStatus());
    }
}