[Junit] MockMvc

Lee Seung Jae·2021년 6월 29일
0

Mock

목록 보기
2/2

MockMvc

MockMvc란 실제 객체와 비슷한데 Test를 할때 필요한 기능만 가지는 가짜 객체를 만들어 스프링MVC 동작을 재현할 수 있는 클래스이다.

build.gradle

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

의존성을 추가해준다.

가장 간단한 GET방식을 알아볼 것인데, Http Method의 post, put, patch, delete 들은 어디서 넣으면 테스트 할 수 있는지 별도의 주석으로 첨부하도록 하겠다.

Controller 추가

일단 Controller를 추가해준다.

@RestController
public class MockTestController{
    
    @GetMapping("/mockTest")
    public String mockTest(@RequestParam String name){
        return name + "님 안녕하세요.";
    }
}

요청 파라미터로 name값을 받아서 안녕하세요를 추가하여 반환해주는 컨트롤러를 작성했다.

Test Code 작성

MockTestController를 테스트하는 클래스를 만들어준다.

@ExtendWith(SpringExtension.class)
@WebMvcTest(MockTestController.class)
public class MockTestControllerTest{
    @Autowired
    private MockMvc mockMvc;
    
    @Test
    @DisplayName("mockMvc 테스트") //이 DisplayName은 임의로 준 것이기 때문에 안써도 무방하다.
    void 테스트_GET() throws Exception{
        MultiValueMap<String, String> initDatas = new LinkedMultiValueMap<>();
        
        initDatas.add("name", "홍길동");
        
        mockMvc.perform(get("/mockTest") // get, post, delete, put, patch를 여기서 매칭시킴
               .params(initDatas))
               .andExpect(status().isOk())
               .andExpect(content().string("홍길동님 안녕하세요"))
               .andDo(print());
    }
}

MockMvc 메소드 정리

  • perform() : 요청을 전송할 때 사용함.
    • 결과 값으로 ResultAction 객체를 받고, 이 객체는 반환값을 검증이나 확인을 하는 andExpect() 메소드 제공 perform(RequestBuilder requestBuilder) - 공식문서 참조
  • get("/mockTest") : Http 메소드를 결정하는 곳(get(), post(), delete(), put(), patch())
    • 괄호 안에는 url 경로를 매칭시킨다.
    • contentType(MediaType type) : json parse
    • content(ObjectMapper) : 요청하는 컨텐츠 contentType으로 변경되어 body에 들어감
  • params(initDatas) : 키,값 파라미터 전달함. 한개일때 param(), 여러개일때 params()
  • andExpect() : 응답을 검증
    • status() : 상태코드를 나타냄. 뒤에 메소드 체이닝으로 ResultMatcher 메소드를 잇는다. 여기선 자주 쓰는것만 정리하겠다.
      • isOk() : HttpStatus 200
      • isCreated() : 201
      • isNotFound() : 404
      • isInternalServerError() : 500
      • is(int status) : HttpStatus 직접 할당
    • view()
      • 뷰 이름 검증
      • view().name("aaa") : 뷰 이름이 aaa인가
    • content() : 응답정보에 대한 검증
      • string() : 괄호안 문자를 포함하는지
  • andDo(print()) : test 응답 결과에 대한 모든 것을 출력한다.

이런식으로 mocking을 하여 테스트를 진행할 수 있다.
이것으로 http method를 다양하게 테스트 해볼 수 있게 되었다.

profile
💻 많이 짜보고 많이 경험해보자 https://lsj8367.tistory.com/ 블로그 주소 옮김

0개의 댓글

Powered by GraphCDN, the GraphQL CDN