diff --git a/src/main/java/umc/kkijuk/server/member/controller/EmailAuthController.java b/src/main/java/umc/kkijuk/server/member/controller/EmailAuthController.java index 42e34761..304953e7 100644 --- a/src/main/java/umc/kkijuk/server/member/controller/EmailAuthController.java +++ b/src/main/java/umc/kkijuk/server/member/controller/EmailAuthController.java @@ -9,7 +9,7 @@ import umc.kkijuk.server.member.emailauth.MailAddressDto; import umc.kkijuk.server.member.emailauth.MailCertificationDto; import umc.kkijuk.server.member.emailauth.MailCertificationResponse; -import umc.kkijuk.server.member.emailauth.MailService; +import umc.kkijuk.server.member.emailauth.MailServiceImpl; @Tag(name = "auth", description = "이메일 인증 API") @RestController @@ -17,7 +17,7 @@ @RequiredArgsConstructor public class EmailAuthController { - private final MailService mailService; + private final MailServiceImpl mailService; @Operation( summary = "이메일 인증번호 요청", diff --git a/src/main/java/umc/kkijuk/server/member/controller/MemberController.java b/src/main/java/umc/kkijuk/server/member/controller/MemberController.java index 30d42411..e6012cba 100644 --- a/src/main/java/umc/kkijuk/server/member/controller/MemberController.java +++ b/src/main/java/umc/kkijuk/server/member/controller/MemberController.java @@ -10,6 +10,7 @@ import umc.kkijuk.server.member.controller.response.*; import umc.kkijuk.server.member.domain.Member; import umc.kkijuk.server.member.dto.*; +import umc.kkijuk.server.member.emailauth.MailServiceImpl; import umc.kkijuk.server.member.service.MemberService; import lombok.RequiredArgsConstructor; @@ -23,7 +24,7 @@ public class MemberController { private final MemberService memberService; -// private final MailService mailService; + private final MailServiceImpl mailService; private int authRandomNumber; // 이메일 인증 숫자를 저장하는 변수 @Operation( @@ -43,7 +44,7 @@ public ResponseEntity saveMember(@RequestBody @Valid Membe description = "회원가입시 이메일 중복을 확인합니다.") @PostMapping("/confirmEmail") public ResponseEntity confirmEmail(@RequestBody MemberEmailDto memberEmailDto){ - Boolean result = memberService.confirmDupEmail(memberEmailDto); + Boolean result = mailService.confirmDupEmail(memberEmailDto); return ResponseEntity.ok(result); } diff --git a/src/main/java/umc/kkijuk/server/member/emailauth/MailService.java b/src/main/java/umc/kkijuk/server/member/emailauth/MailService.java index 440b5eee..053eae8d 100644 --- a/src/main/java/umc/kkijuk/server/member/emailauth/MailService.java +++ b/src/main/java/umc/kkijuk/server/member/emailauth/MailService.java @@ -1,78 +1,12 @@ package umc.kkijuk.server.member.emailauth; -import jakarta.mail.MessagingException; -import jakarta.mail.internet.MimeMessage; -import lombok.RequiredArgsConstructor; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.mail.javamail.JavaMailSender; -import org.springframework.stereotype.Service; -import umc.kkijuk.server.common.domian.exception.CertificationNumberMismatchException; -import umc.kkijuk.server.common.domian.exception.MemberAlreadyExistsException; -import umc.kkijuk.server.member.repository.MemberJpaRepository; +import umc.kkijuk.server.member.dto.MemberEmailDto; -import java.util.Random; +public interface MailService { -@Service -@RequiredArgsConstructor -public class MailService { + MailCertificationResponse sendMail(String mail); - private final MailCertification mailCertification; - private final JavaMailSender javaMailSender; - private final MemberJpaRepository memberJpaRepository; + Boolean verifyMail(MailCertificationDto requestDto); - @Value("${spring.mail.username}") - private String senderEmail; - - - private String createRandomNumber() { - Random rand = new Random(); - String randomNum = ""; - for (int i = 0; i < 6; i++) { - String random = Integer.toString(rand.nextInt(10)); - randomNum += random; - } - - return randomNum; - } - - public MailCertificationResponse sendMail(String mail) { - if(memberJpaRepository.findByEmail(mail).isPresent()){ - throw new MemberAlreadyExistsException(); - } - - MimeMessage message = javaMailSender.createMimeMessage(); - String randomNum = createRandomNumber(); - - try { - message.setFrom(senderEmail); - message.setRecipients(MimeMessage.RecipientType.TO, mail); - message.setSubject("이메일 인증"); - String body = ""; - body += "

" + "요청하신 인증 번호입니다." + "

"; - body += "

" + randomNum + "

"; - body += "

" + "감사합니다." + "

"; - message.setText(body,"UTF-8", "html"); - } catch (MessagingException e) { - e.printStackTrace(); - } - - javaMailSender.send(message); - mailCertification.createMailCertification(mail,randomNum); - return new MailCertificationResponse(mail, randomNum); - } - - // 인증 번호 검증 - public Boolean verifyMail(MailCertificationDto requestDto) { - if (isVerify(requestDto)) { - throw new CertificationNumberMismatchException(); - } - mailCertification.deleteMailCertification(requestDto.getEmail()); - - return true; - } - private boolean isVerify(MailCertificationDto requestDto) { - return !(mailCertification.hasKey(requestDto.getEmail()) && - mailCertification.getMailCertification(requestDto.getEmail()) - .equals(requestDto.getAuthNumber())); - } -} \ No newline at end of file + Boolean confirmDupEmail(MemberEmailDto memberEmailDto); +} diff --git a/src/main/java/umc/kkijuk/server/member/emailauth/MailServiceImpl.java b/src/main/java/umc/kkijuk/server/member/emailauth/MailServiceImpl.java new file mode 100644 index 00000000..97ee81f3 --- /dev/null +++ b/src/main/java/umc/kkijuk/server/member/emailauth/MailServiceImpl.java @@ -0,0 +1,91 @@ +package umc.kkijuk.server.member.emailauth; + +import jakarta.mail.MessagingException; +import jakarta.mail.internet.MimeMessage; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.stereotype.Service; +import umc.kkijuk.server.common.domian.exception.CertificationNumberMismatchException; +import umc.kkijuk.server.common.domian.exception.MemberAlreadyExistsException; +import umc.kkijuk.server.member.domain.Member; +import umc.kkijuk.server.member.dto.MemberEmailDto; +import umc.kkijuk.server.member.repository.MemberRepository; + +import java.util.Optional; +import java.util.Random; + +@Service +@RequiredArgsConstructor +public class MailServiceImpl implements MailService{ + + private final MailCertification mailCertification; + private final JavaMailSender javaMailSender; + private final MemberRepository memberRepository; + + @Value("${spring.mail.username}") + private String senderEmail; + + + private String createRandomNumber() { + Random rand = new Random(); + String randomNum = ""; + for (int i = 0; i < 6; i++) { + String random = Integer.toString(rand.nextInt(10)); + randomNum += random; + } + + return randomNum; + } + + public MailCertificationResponse sendMail(String mail) { + if(memberRepository.findByEmail(mail).isPresent()){ + throw new MemberAlreadyExistsException(); + } + + MimeMessage message = javaMailSender.createMimeMessage(); + String randomNum = createRandomNumber(); + + try { + message.setFrom(senderEmail); + message.setRecipients(MimeMessage.RecipientType.TO, mail); + message.setSubject("이메일 인증"); + String body = ""; + body += "

" + "요청하신 인증 번호입니다." + "

"; + body += "

" + randomNum + "

"; + body += "

" + "감사합니다." + "

"; + message.setText(body,"UTF-8", "html"); + } catch (MessagingException e) { + e.printStackTrace(); + } + + javaMailSender.send(message); + mailCertification.createMailCertification(mail,randomNum); + return new MailCertificationResponse(mail, randomNum); + } + + // 인증 번호 검증 + public Boolean verifyMail(MailCertificationDto requestDto) { + if (isVerify(requestDto)) { + throw new CertificationNumberMismatchException(); + } + mailCertification.deleteMailCertification(requestDto.getEmail()); + + return true; + } + private Boolean isVerify(MailCertificationDto requestDto) { + return !(mailCertification.hasKey(requestDto.getEmail()) && + mailCertification.getMailCertification(requestDto.getEmail()) + .equals(requestDto.getAuthNumber())); + } + + @Override + public Boolean confirmDupEmail(MemberEmailDto memberEmailDto) { + Optional member = memberRepository.findByEmail(memberEmailDto.getEmail()); + if(member.isEmpty()){ + return true; + }else{ + return false; + } + } +} \ No newline at end of file diff --git a/src/main/java/umc/kkijuk/server/member/repository/MemberRepository.java b/src/main/java/umc/kkijuk/server/member/repository/MemberRepository.java new file mode 100644 index 00000000..227f3b19 --- /dev/null +++ b/src/main/java/umc/kkijuk/server/member/repository/MemberRepository.java @@ -0,0 +1,11 @@ +package umc.kkijuk.server.member.repository; + +import umc.kkijuk.server.member.domain.Member; + +import java.util.Optional; + +public interface MemberRepository { + Optional findById(Long id); + Optional findByEmail(String email); + Member save(Member member); +} \ No newline at end of file diff --git a/src/main/java/umc/kkijuk/server/member/repository/MemberRepositoryImpl.java b/src/main/java/umc/kkijuk/server/member/repository/MemberRepositoryImpl.java new file mode 100644 index 00000000..73c3686d --- /dev/null +++ b/src/main/java/umc/kkijuk/server/member/repository/MemberRepositoryImpl.java @@ -0,0 +1,28 @@ +package umc.kkijuk.server.member.repository; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Repository; +import umc.kkijuk.server.member.domain.Member; + +import java.util.Optional; + +@Repository +@RequiredArgsConstructor +public class MemberRepositoryImpl implements MemberRepository{ + private final MemberJpaRepository memberJpaRepository; + + @Override + public Optional findById(Long id) { + return memberJpaRepository.findById(id); + } + + @Override + public Optional findByEmail(String email) { + return memberJpaRepository.findByEmail(email); + } + + @Override + public Member save(Member member) { + return memberJpaRepository.save(member); + } +} \ No newline at end of file diff --git a/src/main/java/umc/kkijuk/server/member/service/MemberService.java b/src/main/java/umc/kkijuk/server/member/service/MemberService.java index fea7f270..ed41550d 100644 --- a/src/main/java/umc/kkijuk/server/member/service/MemberService.java +++ b/src/main/java/umc/kkijuk/server/member/service/MemberService.java @@ -19,7 +19,7 @@ public interface MemberService { Member changeMemberPassword(Long memberId, MemberPasswordChangeDto memberPasswordChangeDto); Member myPagePasswordAuth(Long memberId, MyPagePasswordAuthDto myPagePasswordAuthDto); MemberEmailResponse getMemberEmail(Long memberId); - EmailAuthResponse getEmailAuth(EmailAddressDto emailAddressDto, int number); +// EmailAuthResponse getEmailAuth(EmailAddressDto emailAddressDto, int number); MemberStateResponse changeMemberState(Long memberId); - Boolean confirmDupEmail(MemberEmailDto memberEmailDto); + } diff --git a/src/main/java/umc/kkijuk/server/member/service/MemberServiceImpl.java b/src/main/java/umc/kkijuk/server/member/service/MemberServiceImpl.java index 925c9c75..3c5bab6f 100644 --- a/src/main/java/umc/kkijuk/server/member/service/MemberServiceImpl.java +++ b/src/main/java/umc/kkijuk/server/member/service/MemberServiceImpl.java @@ -13,6 +13,7 @@ import umc.kkijuk.server.member.domain.State; import umc.kkijuk.server.member.dto.*; import umc.kkijuk.server.member.repository.MemberJpaRepository; +import umc.kkijuk.server.member.repository.MemberRepository; import java.util.List; import java.util.Optional; @@ -21,12 +22,12 @@ @Transactional(readOnly = true) @RequiredArgsConstructor public class MemberServiceImpl implements MemberService { - private final MemberJpaRepository memberJpaRepository; + private final MemberRepository memberRepository; private final PasswordEncoder passwordEncoder; @Override public Member getById(Long memberId) { - return memberJpaRepository.findById(memberId) + return memberRepository.findById(memberId) .orElseThrow(() -> new ResourceNotFoundException("Member", memberId)); } @@ -43,7 +44,7 @@ public Member join(MemberJoinDto memberJoinDto) { String encodedPassword = passwordEncoder.encode(memberJoinDto.getPassword()); joinMember.changeMemberPassword(encodedPassword); - return memberJpaRepository.save(joinMember); + return memberRepository.save(joinMember); } @Override @@ -85,7 +86,7 @@ public Member updateMemberField(Long memberId, MemberFieldDto memberFieldDto){ if(!member.getField().equals(memberFieldDto.getField())){ throw new FieldUpdateException(); } - return memberJpaRepository.save(member); + return memberRepository.save(member); } @Override @@ -96,7 +97,7 @@ public Member updateMemberInfo(Long memberId, MemberInfoChangeDto memberInfoChan throw new InvalidMemberDataException(); } member.changeMemberInfo(memberInfoChangeDto.getPhoneNumber(), memberInfoChangeDto.getBirthDate(), memberInfoChangeDto.getMarketingAgree()); - return memberJpaRepository.save(member); + return memberRepository.save(member); } @Override @@ -113,7 +114,7 @@ public Member changeMemberPassword(Long memberId, MemberPasswordChangeDto member String encodedPassword = passwordEncoder.encode(memberPasswordChangeDto.getNewPassword()); member.changeMemberPassword(encodedPassword); - return memberJpaRepository.save(member); + return memberRepository.save(member); } @Override @@ -127,15 +128,6 @@ public Member myPagePasswordAuth(Long memberId, MyPagePasswordAuthDto myPagePass return member; } - @Override - @Transactional - public EmailAuthResponse getEmailAuth(EmailAddressDto emailAddressDto, int authRandomNumber){ - return EmailAuthResponse.builder() - .email(emailAddressDto.getEmail()) - .authNumber(authRandomNumber) - .build(); - } - @Override @Transactional public MemberStateResponse changeMemberState(Long memberId){ @@ -147,21 +139,22 @@ else if(member.getUserState().equals(State.ACTIVATE)){ member.inactivate(); } - memberJpaRepository.save(member); + memberRepository.save(member); return MemberStateResponse.builder() .deleteDate(member.getDeleteDate()) .build(); } - @Override - public Boolean confirmDupEmail(MemberEmailDto memberEmailDto) { - Optional member = memberJpaRepository.findByEmail(memberEmailDto.getEmail()); - if(member.isEmpty()){ - return true; - }else{ - return false; - } - } +// @Override +// @Transactional +// public EmailAuthResponse getEmailAuth(EmailAddressDto emailAddressDto, int authRandomNumber){ +// return EmailAuthResponse.builder() +// .email(emailAddressDto.getEmail()) +// .authNumber(authRandomNumber) +// .build(); +// } + + } diff --git a/src/test/java/umc/kkijuk/server/member/mock/FakeMemberRepository.java b/src/test/java/umc/kkijuk/server/member/mock/FakeMemberRepository.java new file mode 100644 index 00000000..438c5c8f --- /dev/null +++ b/src/test/java/umc/kkijuk/server/member/mock/FakeMemberRepository.java @@ -0,0 +1,41 @@ +package umc.kkijuk.server.member.mock; + +import umc.kkijuk.server.member.domain.Member; +import umc.kkijuk.server.member.repository.MemberRepository; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicLong; + +public class FakeMemberRepository implements MemberRepository { + private final AtomicLong authGeneratedID = new AtomicLong(0); + private final List data = new ArrayList(); + + @Override + public Member save(Member member) { + if (member.getId() == null || member.getId() == 0){ + data.add(member); + return member; + } else { + data.removeIf(item -> Objects.equals(item.getId(), member.getId())); + data.add(member); + return member; + } + } + + @Override + public Optional findById(Long id) { + return data.stream() + .filter(item -> item.getId().equals(id)) + .findAny(); + } + + @Override + public Optional findByEmail(String email) { + return data.stream() + .filter(item -> item.getEmail().equals(email)) + .findAny(); + } +} \ No newline at end of file diff --git a/src/test/java/umc/kkijuk/server/member/mock/FakePasswordEncoder.java b/src/test/java/umc/kkijuk/server/member/mock/FakePasswordEncoder.java new file mode 100644 index 00000000..c8478aa5 --- /dev/null +++ b/src/test/java/umc/kkijuk/server/member/mock/FakePasswordEncoder.java @@ -0,0 +1,15 @@ +package umc.kkijuk.server.member.mock; + +import org.springframework.security.crypto.password.PasswordEncoder; + +public class FakePasswordEncoder implements PasswordEncoder { + @Override + public String encode(CharSequence rawPassword) { + return null; + } + + @Override + public boolean matches(CharSequence rawPassword, String encodedPassword) { + return false; + } +} diff --git a/src/test/java/umc/kkijuk/server/member/service/MailServiceTest.java b/src/test/java/umc/kkijuk/server/member/service/MailServiceTest.java new file mode 100644 index 00000000..c5ada5d1 --- /dev/null +++ b/src/test/java/umc/kkijuk/server/member/service/MailServiceTest.java @@ -0,0 +1,148 @@ +package umc.kkijuk.server.member.service; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.security.crypto.password.PasswordEncoder; +import umc.kkijuk.server.common.domian.exception.CertificationNumberMismatchException; +import umc.kkijuk.server.common.domian.exception.MemberAlreadyExistsException; +import umc.kkijuk.server.member.domain.MarketingAgree; +import umc.kkijuk.server.member.domain.Member; +import umc.kkijuk.server.member.domain.State; +import umc.kkijuk.server.member.dto.MemberEmailDto; +import umc.kkijuk.server.member.emailauth.*; +import umc.kkijuk.server.member.mock.FakeMemberRepository; +import umc.kkijuk.server.member.mock.FakePasswordEncoder; +import umc.kkijuk.server.member.repository.MemberRepository; + +import jakarta.mail.MessagingException; +import jakarta.mail.internet.MimeMessage; +import org.springframework.mail.javamail.JavaMailSender; + +import java.time.LocalDate; +import java.util.List; + +import static org.assertj.core.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.mockito.Mockito.*; + +public class MailServiceTest { + + private MailService mailService; + private MailCertification mailCertification; + private JavaMailSender javaMailSender; + private MemberRepository memberRepository; + + private final String testMemberEmail = "test@naver.com"; + + @BeforeEach + void init() { + mailCertification = mock(MailCertification.class); + javaMailSender = mock(JavaMailSender.class); + memberRepository = new FakeMemberRepository(); + + this.mailService = new MailServiceImpl(mailCertification, javaMailSender, memberRepository); + + Member member = Member.builder() + .email(testMemberEmail) + .name("홍길동") + .phoneNumber("01012345678") + .birthDate(LocalDate.of(1999, 3, 31)) + .password("testpassword") + .marketingAgree(MarketingAgree.BOTH) + .userState(State.ACTIVATE) + .field(List.of("game", "computer")) + .build(); + + memberRepository.save(member); + } + + @Test + void sendMail_이미존재하는이메일_예외발생() { + // given + MemberEmailDto memberEmailDto = new MemberEmailDto(testMemberEmail); + + // then + assertThatThrownBy(() -> mailService.sendMail(testMemberEmail)) + .isInstanceOf(MemberAlreadyExistsException.class); + } + + @Test + void sendMail_새로운이메일_메일발송성공() throws MessagingException { + // given + String newEmail = "newuser@example.com"; + MimeMessage mimeMessage = mock(MimeMessage.class); + doReturn(mimeMessage).when(javaMailSender).createMimeMessage(); + + // when + MailCertificationResponse response = mailService.sendMail(newEmail); + + // then + assertAll( + () -> assertThat(response.getEmail()).isEqualTo(newEmail), + () -> assertThat(response.getAuthNumber()).hasSize(6), + () -> verify(javaMailSender).send(mimeMessage), + () -> verify(mailCertification).createMailCertification(eq(newEmail), anyString()) + ); + } + + @Test + void verifyMail_인증성공() { + // given + String authNumber = "123456"; + MailCertificationDto requestDto = new MailCertificationDto(testMemberEmail, authNumber); + + doReturn(true).when(mailCertification).hasKey(testMemberEmail); + doReturn(authNumber).when(mailCertification).getMailCertification(testMemberEmail); + + // when + Boolean result = mailService.verifyMail(requestDto); + + // then + assertAll( + () -> assertThat(result).isTrue(), + () -> verify(mailCertification).deleteMailCertification(testMemberEmail) + ); + } + + @Test + void verifyMail_인증번호불일치_예외발생() { + // given + String correctAuthNumber = "123456"; + String incorrectAuthNumber = "654321"; + MailCertificationDto requestDto = new MailCertificationDto(testMemberEmail, incorrectAuthNumber); + + doReturn(true).when(mailCertification).hasKey(testMemberEmail); + doReturn(correctAuthNumber).when(mailCertification).getMailCertification(testMemberEmail); + + // then + assertThatThrownBy(() -> mailService.verifyMail(requestDto)) + .isInstanceOf(CertificationNumberMismatchException.class); + + verify(mailCertification, never()).deleteMailCertification(testMemberEmail); + } + + @Test + void confirmDupEmail_이메일중복확인_존재하는이메일() { + // given + MemberEmailDto memberEmailDto = new MemberEmailDto(testMemberEmail); + + // when + Boolean isDup = mailService.confirmDupEmail(memberEmailDto); + + // then + assertThat(isDup).isFalse(); // 이미 존재하므로 중복됨 + } + + @Test + void confirmDupEmail_이메일중복확인_없는이메일() { + // given + String newEmail = "newuser@example.com"; + MemberEmailDto memberEmailDto = new MemberEmailDto(newEmail); + + // when + Boolean isDup = mailService.confirmDupEmail(memberEmailDto); + + // then + assertThat(isDup).isTrue(); // 존재하지 않으므로 중복 아님 + } +} \ No newline at end of file diff --git a/src/test/java/umc/kkijuk/server/member/service/MemberServiceTest.java b/src/test/java/umc/kkijuk/server/member/service/MemberServiceTest.java index f29f5801..6e046de2 100644 --- a/src/test/java/umc/kkijuk/server/member/service/MemberServiceTest.java +++ b/src/test/java/umc/kkijuk/server/member/service/MemberServiceTest.java @@ -2,214 +2,32 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.annotation.DirtiesContext; -import umc.kkijuk.server.member.controller.response.MemberFieldResponse; -import umc.kkijuk.server.member.controller.response.MemberInfoResponse; -import umc.kkijuk.server.common.domian.exception.ConfirmPasswordMismatchException; -import umc.kkijuk.server.member.domain.MarketingAgree; +import org.springframework.security.crypto.password.PasswordEncoder; +import umc.kkijuk.server.member.controller.response.EmailAuthResponse; import umc.kkijuk.server.member.domain.Member; -import umc.kkijuk.server.member.domain.State; -import umc.kkijuk.server.member.dto.MemberFieldDto; -import umc.kkijuk.server.member.dto.MemberInfoChangeDto; -import umc.kkijuk.server.member.dto.MemberJoinDto; -import umc.kkijuk.server.member.repository.MemberJpaRepository; +import umc.kkijuk.server.member.dto.*; +import umc.kkijuk.server.member.emailauth.MailService; +import umc.kkijuk.server.member.mock.FakeMemberRepository; +import umc.kkijuk.server.member.repository.MemberRepository; -import java.time.LocalDate; -import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.jupiter.api.Assertions.*; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.mockito.Mockito.mock; -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -public class MemberServiceTest { - @Autowired - MemberService memberService; +class MemberServiceTest { - @Autowired - MemberJpaRepository memberJpaRepository; - - @Autowired - private TestRestTemplate restTemplate; + private MemberService memberService; + private MemberRepository memberRepository; + private PasswordEncoder passwordEncoder; + private MailService mailService; @BeforeEach - public void setUp() { - Member member = new Member("test@naver.com", "홍길동", - "01012345678", LocalDate.parse("1999-03-31"), - "testpassword", MarketingAgree.BOTH, State.ACTIVATE); - member.changeFieldInfo(List.of("game", "computer")); - memberJpaRepository.save(member); - } - - private String testMemberEmail = "asd@naver.com"; - @Test - @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) - public void 유저정보db저장및조회() throws Exception { - // given - MemberJoinDto memberJoinDto = new MemberJoinDto(testMemberEmail, "홍길동", "010-7444-1768", LocalDate.parse("1999-03-31"), "passwordTest", "passwordTest", MarketingAgree.BOTH, State.ACTIVATE); - - // when - Member joinMember = memberService.join(memberJoinDto); - - // then - assertAll( - () -> assertEquals(joinMember.getEmail(), testMemberEmail), - () -> assertEquals(joinMember.getName(), "홍길동") - ); - } - - @Test - @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) - public void joinExceptionWIthPasswordIncorrect() { - // given - MemberJoinDto memberJoinDto = new MemberJoinDto(testMemberEmail, "홍길동", "010-7444-1768", LocalDate.parse("1999-03-31"), "passwordTest", "incorrectPassword", MarketingAgree.BOTH, State.ACTIVATE); - - // when - // then - assertThatThrownBy(() -> memberService.join(memberJoinDto)) - .isInstanceOf(ConfirmPasswordMismatchException.class); - } - - - @Test - @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) - public void 회원가입성공() { - // given - MemberJoinDto memberJoinDto = MemberJoinDto.builder() - .email("asd@naver.com") - .name("홍길동") - .phoneNumber("010-7444-1768") - .birthDate(LocalDate.parse("1999-03-31")) - .password("passwordTest") - .passwordConfirm("passwordTest") - .marketingAgree(MarketingAgree.BOTH) - .userState(State.ACTIVATE) - .build(); - - HttpEntity request = new HttpEntity<>(memberJoinDto); - - // when - ResponseEntity response = restTemplate.postForEntity("/member", request, String.class); - - // then - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED); - assertThat(response.getBody()).contains("Member created successfully"); + void setUp() { + memberRepository = new FakeMemberRepository(); + passwordEncoder = mock(PasswordEncoder.class); + memberService = new MemberServiceImpl(memberRepository, passwordEncoder); } -// @Test -// @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) -// public void 회원가입실패_비밀번호불일치() { -// // given -// MemberJoinDto memberJoinDto = MemberJoinDto.builder() -// .email("asd@naver.com") -// .name("홍길동") -// .phoneNumber("010-7444-1768") -// .birthDate(LocalDate.parse("1999-03-31")) -// .password("passwordTest") -// .passwordConfirm("wrongPassword") -// .marketingAgree(MarketingAgree.BOTH) -// .userState(State.ACTIVATE) -// .build(); -// -// HttpEntity request = new HttpEntity<>(memberJoinDto); -// -// // when -// ResponseEntity response = restTemplate.postForEntity("/member", request, String.class); -// -// // then -// assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); -// assertThat(response.getBody()).contains("비밀번호가 일치하지 않습니다."); -// } - - @Test - @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) - public void 내정보_조회_성공() { - // Given - - // When - ResponseEntity response = restTemplate.getForEntity("/member/myPage/info", MemberInfoResponse.class); - - // Then - assertEquals(HttpStatus.OK, response.getStatusCode()); - - MemberInfoResponse body = response.getBody(); - assertNotNull(body); - assertEquals("test@naver.com", body.getEmail()); - assertEquals("홍길동", body.getName()); - assertEquals("01012345678", body.getPhoneNumber()); - assertEquals(LocalDate.parse("1999-03-31"), body.getBirthDate()); - } - - @Test - @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) - public void 내정보_수정() { - // Given - - MemberInfoChangeDto changeDto = MemberInfoChangeDto.builder() - .phoneNumber("010-5678-1234") - .birthDate(LocalDate.parse("2000-01-01")) - .marketingAgree(MarketingAgree.EMAIL) - .build(); - - HttpEntity requestEntity = new HttpEntity<>(changeDto); - - // When - ResponseEntity response = restTemplate.exchange("/member/myPage/info", HttpMethod.PUT, requestEntity, Boolean.class); - - // Then - assertEquals(HttpStatus.OK, response.getStatusCode()); - Boolean body = response.getBody(); - assertNotNull(body); - assertEquals(true, body); - - // Verify changes - Member updatedMember = memberJpaRepository.findById(1L).orElse(null); - assertNotNull(updatedMember); - assertEquals("010-5678-1234", updatedMember.getPhoneNumber()); - assertEquals(LocalDate.parse("2000-01-01"), updatedMember.getBirthDate()); - assertEquals(MarketingAgree.EMAIL, updatedMember.getMarketingAgree()); - } - - @Test - @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) - public void 관심분야_조회(){ - // 회원추가 - - ResponseEntity response = restTemplate.getForEntity("/member/myPage/field", MemberFieldResponse.class); - - assertEquals(HttpStatus.OK, response.getStatusCode()); - MemberFieldResponse body = response.getBody(); - assertNotNull(body); - assertEquals(List.of("game", "computer"), body.getField()); - } - - - @Test - @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) - public void 관심분야_수정(){ - //given - - MemberFieldDto memberFieldDto = MemberFieldDto.builder().field(List.of("book", "movie")).build(); - HttpEntity request = new HttpEntity<>(memberFieldDto); - //when - ResponseEntity response = restTemplate.postForEntity("/member/myPage/field", request, Boolean.class); - //then - assertEquals(HttpStatus.OK, response.getStatusCode()); - Boolean body = response.getBody(); - assertNotNull(body); - assertEquals(true, body); - - Member updatedMember = memberJpaRepository.findById(1L).orElse(null); - assertNotNull(updatedMember); - assertEquals(List.of("book", "movie"), updatedMember.getField()); - } } \ No newline at end of file