Mock이란 모조품이라는 뜻으로, Mock 객체란 실제의 모듈을 흉내내는 가짜 모듈을 작성하여 테스트의 효용성을 높이는 데 사용하는 객체.
mock을 쉽게 만들고 mock의 행동을 정하는 stubbing이나 정상적으로 작동하는지에 대한 verify 등 다양한 기능을 제공해주는 프레임워크.
Mock 객체를 직접 구현하지 않아도 됨.
implementation 'org.mockito:mockito-android:3.7.7’
브라우저에서 요청과 응답을 의마하는 객체로서 Controller 테스트를 용이하게 해주는 라이브러리.
//@SpringBootTest //Junit5 - Runwith 포함
@RunWith(SpringRunner.class)
//Controller + Spring security 추가
@WebMvcTest(controllers = {PostController.class}, includeFilters = @ComponentScan.Filter(classes = {EnableWebSecurity.class}))
//@AutoConfigureMockMvc //@Service, @Repository가 붙은 객체들도 모두 메모리에 올림
@RequestMapping("/api")
class PostControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void postList_GET() throws Exception {
// 키의 중복값을 허용하는 MultiValueMap
MultiValueMap<String, String> query_param = new LinkedMultiValueMap<>();
query_param.add("page","1");
query_param.add("sorted","createdAt");
mockMvc.perform(MockMvcRequestBuilders.get("/posts?page=1&sorted=createdAt"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
mockMvc.perform(MockMvcRequestBuilders.get("/posts").params(query_param))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
}
perform() : 요청을 전송하는 역할. 결과로 ResultActions 객체를 받으며, ResultActions 객체는 리턴 값을 검증하고 확인할 수 있는 andExcpect() 메소드를 제공
andExpect() : 응답을 검증하는 역할.
get("/mock/blog") : HTTP 메소드를 결정. 경로를 인자로 보내줌.
params(info) : 키=값의 파라미터를 전달.
여러 개일 때 → params(), 하나일 때 → param()