Mock
Mock의 필요성
Mockito
@SpringBootTest
@AutoConfigureMockMvc
class MemberControllerMockTest {
// @Autowired를 통해 Spring Bean에 등록된 객체 중비
@Autowired private MockMvc mockMvc;
@Autowired private Gson gson;
// @MockBean : 가짜 객체를 주입
@MockBean private MemberService memberService;
@MockBean private MemberMapper mapper;
@Test
void postMemberTest() throws Exception {
// given (조건 구성)
MemberDto.Post post = new MemberDto.Post("hgd@gmail.com", "홍길동", "010-1234-5678");
Member member = new Member("hgd@gmail.com", "홍길동", "010-1234-5678") // (3)
member.setStamp(new Stamp());
// Test 하는 도중, Mock 객체로 만든 부분을 사용하는 메서드에서 나오는 결과값을 지정
given(mapper.memberPostDtoToMember(Mockito.any(MemberDto.Post.class)))
.willReturn(member);
given(memberService.createMember(Mockito.any(Member.class)))
.willReturn(member);
// when, then 부분 생략
...
}
@WebMvcTest(MemberController.class)
@MockBean(JpaMetamodelMappingContext.class)
public class MemberControllerRestDocsTest {
@Autowired private MockMvc mockMvc;
@Autowired private Gson gson;
@MockBean private MemberService memberService;
@MockBean private MemberMapper mapper;
@Test
public void postMemberTest() throws Exception {
// given (사용할 객체 및 Mock 세팅)
MemberDto.Post post = new MemberDto.Post("hgd@gmail.com", "홍길동", "010-1234-5678");
String content = gson.toJson(post);
MemberDto.response responseDto =
new MemberDto.response(1L, "hgd@gmail.com", "홍길동", "010-1234-5678",
Member.MemberStatus.MEMBER_ACTIVE, new Stamp());
given(mapper.memberPostToMember(Mockito.any(MemberDto.Post.class))).willReturn(new Member());
given(memberService.createMember(Mockito.any(Member.class))).willReturn(new Member());
given(mapper.memberToMemberResponse(Mockito.any(Member.class))).willReturn(responseDto);
// when (HTTP 요청을 보냄)
ResultActions actions =
mockMvc.perform(
post("/v11/members")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(content)
);
// then (검증)
actions.andExpect(status().isCreated())
.andExpect(jsonPath("$.data.email").value(post.getEmail()))
.andExpect(jsonPath("$.data.name").value(post.getName()))
.andExpect(jsonPath("$.data.phone").value(post.getPhone()))
.andReturn()
}
}
관련 어노테이션
@WebMvcTest(Controller.class)
@MockBean(JpaMetamodelMappingContext.class)
@SpringBootTest, @AutoConfigureMockMvc
데이터 액세스 계층 테스트 규칙
// Repository의 기능을 정상적으로 사용하기 위한 Configuration을 Spring이 자동으로 해줌
// (Spring Boot의 일부분 기능)
@DataJpaTest
public class MemberRepositoryTest {
@Autowired
private MemberRepository memberRepository; // Dependency Injection
@Test
public void saveMemberTest() {
// given
Member member = new Member();
member.setEmail("hgd@gmail.com");
member.setName("홍길동");
member.setPhone("010-1111-2222");
// when
Member savedMember = memberRepository.save(member);
// then
assertNotNull(savedMember); // (5-1)
assertTrue(member.getEmail().equals(savedMember.getEmail()));
assertTrue(member.getName().equals(savedMember.getName()));
assertTrue(member.getPhone().equals(savedMember.getPhone()));
}
}
관련 어노테이션