인프런의 "더 자바, 애플리케이션을 테스트하는 다양한 방법”을 보고 정리한 것임
Mock 객체의 행동을 조작하는 것
@Test
void stubbing1Test() {
StudyService studyService = new StudyService(memberService, studyRepository);
assertNotNull(studyService);
Member member = new Member();
member.setId(1L);
member.setEmail("lee@gamil.com");
when(memberService.findById(any())).thenReturn(Optional.of(member));
Study study = new Study(10, "java");
studyService.createNewStudy(1L, study);
}
@Test
void stubbing2Test() {
StudyService studyService = new StudyService(memberService, studyRepository);
assertNotNull(studyService);
Member member = new Member();
member.setId(1L);
member.setEmail("lee@gamil.com");
when(memberService.findById(any())).thenReturn(Optional.of(member));
assertEquals("lee@gamil.com", memberService.findById(1L).get().getEmail());
assertEquals("lee@gamil.com", memberService.findById(2L).get().getEmail());
doThrow(new IllegalArgumentException()).when(memberService).validate(1L);
assertThrows(IllegalArgumentException.class, () -> {
memberService.findById(1L);
});
memberService.validate(2L);
}
@Test
void stubbing3Test() {
StudyService studyService = new StudyService(memberService, studyRepository);
assertNotNull(studyService);
Member member = new Member();
member.setId(1L);
member.setEmail("lee@gamil.com");
when(memberService.findById(any()))
.thenReturn(Optional.of(member))
.thenThrow(new RuntimeException())
.thenReturn(Optional.empty());
Optional<Member> byId = memberService.findById(1L);
assertEquals("lee@gamil.com", byId.get().getEmail());
assertThrows(RuntimeException.class, () -> {
memberService.findById(2L);
});
assertEquals(Optional.empty(), memberService.findById(3L));
}
@Test
void stubbing4Test() {
StudyService studyService = new StudyService(memberService, studyRepository);
assertNotNull(studyService);
Member member = new Member();
member.setId(1L);
member.setEmail("lee@gamil.com");
Study study = new Study(10, "테스트");
// TODO memberService 객체에 findById 메소드를 1L 값으로 호출하면 Optional.of(member) 객체를 리턴하도록 Stubbing
when(memberService.findById(1L)).thenReturn(Optional.of(member));
// TODO studyRepository 객체에 save 메소드를 study 객체로 호출하면 study 객체 그대로 리턴하도록 Stubbing
when(studyRepository.save(study)).thenReturn(study);
studyService.createNewStudy(1L, study);
assertNotNull(study.getOwner());
assertEquals(member, study.getOwner());
}