publicclassMemberService{privatefinalMemberRepositorymemberRepository=newMemoryMemberRepository();publicLongjoin(Membermember){//같은 이름이 있는 중복 회원 XvalidateDuplicatedMember(member);//중복 회원 검증memberRepository.save(member);returnmember.getId();}privatevoidvalidateDuplicatedMember(Membermember){memberRepository.findByName(member.getName()).ifPresent(m->{thrownewIllegalStateException("이미 존재하는 회원입니다.");});}//전체 회원 조회publicList<Member>findMembers(){returnmemberRepository.findAll();}publicOptional<Member>findOne(LongmemberId){returnmemberRepository.findById(memberId);}}
classMemberServiceTest{MemberServicememberService;MemoryMemberRepositoryrepository;@BeforeEachpublicvoidbeforeEach(){repository=newMemoryMemberRepository();memberService=newMemberService(repository);}@AfterEachpublicvoidafterEach(){repository.clearStore();}@Testvoid회원가입(){//givenMembermember=newMember();member.setName("hello");//whenLongsaveId=memberService.join(member);//thenMemberfindMember=memberService.findOne(saveId).get();assertThat(member.getName()).isEqualTo(findMember.getName());}@Testpublicvoid중복_회원_예외(){//givenMembermember1=newMember();member1.setName("spring");Membermember2=newMember();member2.setName("spring");//whenmemberService.join(member1);IllegalStateExceptione=assertThrows(IllegalStateException.class,()->memberService.join(member2));assertThat(e.getMessage()).isEqualTo("이미 존재하는 회원입니다.");}}
@BeforeEach : 각 테스트 실행 전에 호출된다. 테스트가 서로 영향이 없도록 항상 새로운 객체를 생성하고, 의존관계도 새로 맺어준다.