2024.07.23 - [Backend] - [Java Springboot] 이메일 발송 API 코드 리팩토링
개요
SSAFY 자율프로젝트에서 이메일 발송 API를 제작했는데, 이전 글에서도 언급했다시피 코드를 작업하면서 별 문제가 발생하지 않았다. 정말 다행이다 SSAFY에서 프로젝트를 진행해 봤으면 알겠지만 기능 구현만 하기도 매우 벅찬 시간이라 테스트코드? 코드리뷰? 이런건 정말 사치다. 그래서 당시에는 테스트코드를 짜볼 생각조차도 들지 않았는데, 싸피가 끝났고 부족한 부분을 하나씩 채우는 과정에서 테스트코드를 짜보려고 한다.
이메일 테스트코드를 짜는 여러 가지 방법
지금은 지워진 글인데, 해당 글을 보니 이메일 테스트 할 때 실제로 이메일이 발송되는 경우가 있어서 Mockito를 이용해서 테스트를 진행했다는 글을 보았다.
https://jaykaybaek.tistory.com/23
이메일 테스트코드를 짤 때 실제 발송되는 것은 불필요하기 때문에, 실제 발송되지 않게 테스트 하는 방법을 찾아보고자 한다.
그 글을 보고 참고하려고 했으나, 그 글이 사라져서 따라할 수가 없어서 다른 방법을 찾아보고 있다.
다른 분들도 여러 가지 방법을 제안해 주셨다.
내공이 쌓이면 저런 방식도 고려해보려고 한다.
나는 GreenMail로 테스트코드를 짜 보려고 한다. 이 방식은 한국어로 된 참고자료가 많이 없어서, 영어로 된 자료를 많이 참고하였다.
GreenMail이란?
공식 페이지
https://greenmail-mail-test.github.io/greenmail/
GreenMail
Introduction GreenMail is an open source, intuitive and easy-to-use test suite of email servers for testing purposes. Typical use cases include mail integration testing or lightweight sand boxed mail server for development. Supports SMTP, POP3 and IMAP inc
greenmail-mail-test.github.io
package org.example.async_pjt.qna.service;
import com.icegreen.greenmail.configuration.GreenMailConfiguration;
import com.icegreen.greenmail.junit5.GreenMailExtension;
import com.icegreen.greenmail.util.ServerSetupTest;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
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.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class QnaServiceTest {
@RegisterExtension
static GreenMailExtension greenMail = new GreenMailExtension(ServerSetupTest.SMTP)
.withConfiguration(GreenMailConfiguration.aConfig().withUser("lily", "lily"))
.withPerMethodLifecycle(true);
@Autowired
private TestRestTemplate testRestTemplate;
@Test
void shouldNotifyUserViaEmail() throws MessagingException, IOException {
String payload = "{\"email\": \"a@gmail.com\", \"content\": \"Hello World!\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(payload, headers);
ResponseEntity<Void> response = this.testRestTemplate.postForEntity("/api/v1/qna", request, Void.class);
assertEquals(200, response.getStatusCode());
// 이메일 수신 확인
assertTrue(greenMail.waitForIncomingEmail(5000, 1));
MimeMessage[] receivedMessages = greenMail.getReceivedMessages();
assertEquals(1, receivedMessages.length);
assertEquals("내 이메일", receivedMessages[0].getAllRecipients()[0].toString());
assertEquals("이메일 문의", receivedMessages[0].getSubject());
assertTrue(receivedMessages[0].getContent().toString().contains("Hello World!"));
}
}
이메일 테스트 코드는 크게 두 부분으로 구분된다.
일단 코드를 짰는데... 오류가 뜬다.
인텔리제이가 왜 그런지 원인을 잘 쏴준 것도 아니고(열어보라는 파일은 열리지 않는다), 왜 오류가 뜨는지 당최 알 수가 없었다...
아마 이메일 테스트코드 포스팅을 마저 작성한다면, 다른 방식으로도 이것저것 시도해볼 것 같다.
혹시 제가 더 참고해야 할 원인이 있다면, 댓글로 알려주시면 감사하겠습니다..
'Backend' 카테고리의 다른 글
[Java Springboot] gradle 종속성 인식 오류 케이스 정리 (0) | 2024.08.13 |
---|---|
[Java Springboot] 이메일 발송 API 코드 리팩토링 (0) | 2024.07.24 |
[Java Springboot] 이메일 발송 API 만들기 (0) | 2024.07.15 |
lombok.Value vs org.springframework.beans.factory.annotation.Value (1) | 2024.07.08 |
테스트코드를 왜 짜는가?와 테스트코드 짜는 법(Java)(1) (0) | 2024.06.21 |