Slice Test
Mock
not real, but intended to be very similar to a real situation, substance etc
Mock 사용 이유
Mockito
API 계층 (Controller)
@SpringBootTest
@AutoConfigureMockMvc
class MemberControllerMockTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private Gson gson;
// @MockBean : 가짜 객체 주입
@MockBean
private MemberService memberService;
@Autowired
private MemberMapper mapper;
@Test
void postMemberTest() throws Exception {
// given
MemberDto.Post post = new MemberDto.Post(
"hgd@gmail.com",
"홍길동",
"010-1234-5678");
Member member = mapper.memberPostToMember(post);
member.setStamp(new Stamp());
// given()은 Mock 객체 특정 값을 리턴하는 동작 지정
// Mockito의 when()과 동일 기능
given(memberService.createMember(
Mockito.any(Member.class)))
.willReturn(member); // .willReturn()은 리턴할 stub 데이터
String content = gson.toJson(post);
// when
ResultActions actions =
mockMvc.perform(
post("/v11/members")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(content));
// then
MvcResult result =
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();
}
}
서비스 계층
@ExtendWith(MockitoExtension.class)
public class MemberService {
@Mock
private MemberRepository memberRepository;
@InjectMocks
private MemberService memberService;
public Member createMember(Member member) {
verifyExistsEmail(member.getEmail());
Member savedMember = memberRepository.save(member);
publisher.publishEvent(new MemberRegistrationApplicationEvent(this, savedMember));
return savedMember;
}
...
...
private void verifyExistsEmail(String email) {
Optional<Member> member = memberRepository.findByEmail(email);
if (member.isPresent())
throw new BusinessLogicException(ExceptionCode.MEMBER_EXISTS);
}
}