개발/TDD
[Junit] MockMvc란?
도발개발
2022. 9. 20. 17:25
1. MockMvc 란?
MockMvc는 웹 애플리케이션을 애플리케이션 서버에 배포하지 않고 테스트용 MVC 환경을 만들어 요청 및 전송, 응답기능을 제공해주는 유틸리티 클래스다.
2. MockMvc 사용법
get 방식으로 /post를 요청 시 Hello world가 출력되는 controller를 테스트한다고 가정.
Controller 단
@RestController
public class PostController {
@GetMapping("/posts")
public String get(){
return "Hello world";
}
}
Test 단
@WebMvcTest
class PostControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
@DisplayName("/posts 요청시 Hello World를 출력한다.")
void test() throws Exception {
//expected
mockMvc.perform(get("/posts")) //get방식으로 /posts로 요청을 보냄
.andExpect(status().isOk()) //응답 status를 ok로 테스트
.andExpect(content().string("Hello world")) //반환된 응답값을 확인
.andDo(print()); //응답값 print
}
}
3. MockMvcRequestBuilders
- GET/POST/PUT/DELETE 요청 방식과 매핑되는 메서드들을 제공
- HTTP 요청 관련 정보(파라미터, 헤더, 쿠키 등)를 설정
메서드 명 | 설명 |
param / params | 요청 파라미터를 설정한다. |
header / headers | 요청 헤더를 설정한다. contentType이나 accept와 같은 특정 헤더를 설정할 수 있는 메서드도 제공한다. |
cookies | 쿠키를 설정한다. |
content | 요청 본문을 설정한다. |
contentType | 본문 타입을 설정한다. |
requestAttr | 요청 스코프에 객체를 설정한다. |
flashAttr | 플래시 스코프에 객체를 설정한다. |
sessionAttr | 세션 스코프에 객체를 설정한다. |
@Test
@DisplayName("MockMvcRequestBuilders 메서드")
void MockMvcRequestBuilders() throws Exception{
mockMvc.perform(get("/mockMvcRequestBuilders")
.param("testParam","test") // name, values
.content("Json으로")
.contentType(APPLICATION_JSON)
);
}
4. MockMvcResultHandlers
- andDo() 메서드를 이용하여 실행결과를 출력
메서드 명 | 설명 |
log() | 실행결과를 디버깅 레벨로 출력 |
print() | 실행결과를 지정해준 대상으로 출력 |
@Test
@DisplayName("/posts 요청시 Hello World를 출력한다.")
void test() throws Exception {
//expected
mockMvc.perform(get("/posts"))
.andExpect(status().isOk())
.andExpect(content().string("Hello worlds"))
.andDo(print())
.andDo(log());
}
5.MockMvcResultMatchers
- 응답에 대한 검증을 해줌. andExpect()
메서드 명 | 설명 |
status | 상태 코드 검증 |
content | 응답 본문 검증 |
view | 컨트롤러가 반환한 뷰 이름 검증 |
@Test
@DisplayName("/posts 요청시 Hello World를 출력한다.")
void test() throws Exception {
//expected
mockMvc.perform(get("/posts"))
.andExpect(status().isOk())
.andExpect(content().string("Hello worlds"))
.andExpect(view().name("viewName"))
.andDo(print());
}