본문 바로가기
공부/프로그래밍

[SpringBoot] Controller 테스트 작성하기.(Mybatis 테스트 포함)

by demonic_ 2018. 7. 3.
반응형

Controller의 URL호출에 작동하는지 확인하는 Test를 작성합니다. 

해당 프로젝트에 Mybatis 연동을 마친상태라면(예를들어 @MapperScan 어노테이션을 이미 사용한 상태) 에러가 발생하니 

@AutoConfigureMybatis 것을 반드시 추가합니다. 그러지 않으면 아래의 에러가 발생합니다.


org.springframework.beans.factory.BeanCreationException: Error creating bean with name '매퍼인터페이스명' defined in file  

(...) 

Caused by: java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required


Mybatis 를 연동은 생략하겠습니다.



사용하기 전 체크사항

- 컨트롤러를 테스트하기 위해서는 @WebMvcTest 어노테이션을 추가해서 특정 컨트롤러를 지정합니다. 

예) @WebMvcTest(SampleController.class) 

@WebMvcTest 어노테이션을 이용하면 @Controller, @Component, @ControllerAdvice 등 작성된 코드를 인식할 수 있습니다. 


- 컨트롤러를 호출하기 위해선 org.springframework.test.web.servlet.MockMvc 객체를 사용해야 합니다. @WebMvcTest를 같이 사용하면 별도 주입없이 @Autowired만으로 코드를 작성할 수 있습니다.



gradle 에 다음의 것을 추가합니다.


# MockMvc 를 사용하기 위해 추가 

testCompile('org.springframework.restdocs:spring-restdocs-mockmvc') 

# Mybatis 테스트를 위해 추가 

testCompile('org.mybatis.spring.boot:mybatis-spring-boot-starter-test:1.3.2')




컨트롤러 작성(SampleController.class)


/**
 * 샘플 컨트롤러
 */
@RestController
public class SampleController {

    @Autowired
    private MemberMapper memberMapper;

    // String 형 테스트
    @GetMapping(path="/sample/testGetStr")
    public String testGetStr(){
        return "Hello World";
    }

    // Mybatis 로 데이터를 불러와 Json 형 테스트
    @RequestMapping(path="/sample/getTest", method = RequestMethod.GET)
    public MemberDTO getTest(@RequestParam Map param, Model model) throws Exception{
        param.put("CODE", "0000");
        param.put("MESSAGE", "TEST");
        MemberDTO memberDTO = MemberDTO.builder().user_email("TEST").build();
        return memberDTO;
    }
}



테스트 컨트롤러 작성(SampleControllerTests.class)

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.spring.boot.test.autoconfigure.AutoConfigureMybatis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;


@RunWith(SpringRunner.class)
@WebMvcTest(SampleController.class)
@AutoConfigureMybatis 			// Mybatis를 포함하고 있는 프로젝트라면 꼭 사용해주세요.
//@SpringBootTest 					// 해당 어노테이션은 생략합니다.
public class SampleControllerTests {
    @Autowired
    MockMvc mock;

    @Test
    public void testGetStr() throws Exception{
        mock.perform(get("/sample/testGetStr"))
                .andExpect(content().string("Hello World"));
    }

    @Test
    public void testGetTest() throws Exception{
        mock.perform(get("/sample/getTest"))
                .andExpect(content().json("{\"id\":null,\"user_email\":\"TEST\",\"user_name\":null,\"user_status\":null}"));
    }
}


테스트 결과 - 성공




반응형

댓글