add junit test for mail

This commit is contained in:
Ludy87 2025-05-20 22:06:34 +02:00
parent 8bfdb2abb5
commit 9504b359cc
No known key found for this signature in database
GPG Key ID: 92696155E0220F94
4 changed files with 229 additions and 51 deletions

View File

@ -3,6 +3,7 @@ package stirling.software.SPDF.controller.api;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.mail.MailSendException;
import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
@ -53,6 +54,11 @@ public class EmailController {
// Calls the service to send the email with attachment // Calls the service to send the email with attachment
emailService.sendEmailWithAttachment(email); emailService.sendEmailWithAttachment(email);
return ResponseEntity.ok("Email sent successfully"); return ResponseEntity.ok("Email sent successfully");
} catch (MailSendException ex) {
// handles your "Invalid Addresses" case
String errorMsg = ex.getMessage();
log.error("MailSendException: {}", errorMsg, ex);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorMsg);
} catch (MessagingException e) { } catch (MessagingException e) {
// Catches any messaging exception (e.g., invalid email address, SMTP server issues) // Catches any messaging exception (e.g., invalid email address, SMTP server issues)
String errorMsg = "Failed to send email: " + e.getMessage(); String errorMsg = "Failed to send email: " + e.getMessage();

View File

@ -1,5 +1,7 @@
package stirling.software.SPDF.config.security.mail; package stirling.software.SPDF.config.security.mail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -57,4 +59,111 @@ public class EmailServiceTest {
// Verify that the email was sent using mailSender // Verify that the email was sent using mailSender
verify(mailSender).send(mimeMessage); verify(mailSender).send(mimeMessage);
} }
@Test
void testSendEmailWithAttachmentThrowsExceptionForMissingFilename() throws MessagingException {
Email email = new Email();
email.setTo("test@example.com");
email.setSubject("Test Email");
email.setBody("This is a test email.");
email.setFileInput(fileInput);
when(fileInput.isEmpty()).thenReturn(false);
when(fileInput.getOriginalFilename()).thenReturn("");
try {
emailService.sendEmailWithAttachment(email);
fail("Expected MessagingException to be thrown");
} catch (MessagingException e) {
assertEquals("An attachment is required to send the email.", e.getMessage());
}
}
@Test
void testSendEmailWithAttachmentThrowsExceptionForMissingFilenameNull()
throws MessagingException {
Email email = new Email();
email.setTo("test@example.com");
email.setSubject("Test Email");
email.setBody("This is a test email.");
email.setFileInput(fileInput);
when(fileInput.isEmpty()).thenReturn(false);
when(fileInput.getOriginalFilename()).thenReturn(null);
try {
emailService.sendEmailWithAttachment(email);
fail("Expected MessagingException to be thrown");
} catch (MessagingException e) {
assertEquals("An attachment is required to send the email.", e.getMessage());
}
}
@Test
void testSendEmailWithAttachmentThrowsExceptionForMissingFile() throws MessagingException {
Email email = new Email();
email.setTo("test@example.com");
email.setSubject("Test Email");
email.setBody("This is a test email.");
email.setFileInput(fileInput);
when(fileInput.isEmpty()).thenReturn(true);
try {
emailService.sendEmailWithAttachment(email);
fail("Expected MessagingException to be thrown");
} catch (MessagingException e) {
assertEquals("An attachment is required to send the email.", e.getMessage());
}
}
@Test
void testSendEmailWithAttachmentThrowsExceptionForMissingFileNull() throws MessagingException {
Email email = new Email();
email.setTo("test@example.com");
email.setSubject("Test Email");
email.setBody("This is a test email.");
email.setFileInput(null); // Missing file
try {
emailService.sendEmailWithAttachment(email);
fail("Expected MessagingException to be thrown");
} catch (MessagingException e) {
assertEquals("An attachment is required to send the email.", e.getMessage());
}
}
@Test
void testSendEmailWithAttachmentThrowsExceptionForInvalidAddressNull()
throws MessagingException {
Email email = new Email();
email.setTo(null); // Invalid address
email.setSubject("Test Email");
email.setBody("This is a test email.");
email.setFileInput(fileInput);
try {
emailService.sendEmailWithAttachment(email);
fail("Expected MailSendException to be thrown");
} catch (MessagingException e) {
assertEquals("Invalid Addresses", e.getMessage());
}
}
@Test
void testSendEmailWithAttachmentThrowsExceptionForInvalidAddressEmpty()
throws MessagingException {
Email email = new Email();
email.setTo(""); // Invalid address
email.setSubject("Test Email");
email.setBody("This is a test email.");
email.setFileInput(fileInput);
try {
emailService.sendEmailWithAttachment(email);
fail("Expected MailSendException to be thrown");
} catch (MessagingException e) {
assertEquals("Invalid Addresses", e.getMessage());
}
}
} }

View File

@ -0,0 +1,54 @@
package stirling.software.SPDF.config.security.mail;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Properties;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import stirling.software.SPDF.model.ApplicationProperties;
class MailConfigTest {
private ApplicationProperties.Mail mailProps;
@BeforeEach
void initMailProperties() {
mailProps = mock(ApplicationProperties.Mail.class);
when(mailProps.getHost()).thenReturn("smtp.example.com");
when(mailProps.getPort()).thenReturn(587);
when(mailProps.getUsername()).thenReturn("user@example.com");
when(mailProps.getPassword()).thenReturn("password");
}
@Test
void shouldConfigureJavaMailSenderWithCorrectProperties() {
ApplicationProperties appProps = mock(ApplicationProperties.class);
when(appProps.getMail()).thenReturn(mailProps);
MailConfig config = new MailConfig(appProps);
JavaMailSender sender = config.javaMailSender();
assertInstanceOf(JavaMailSenderImpl.class, sender);
JavaMailSenderImpl impl = (JavaMailSenderImpl) sender;
Properties props = impl.getJavaMailProperties();
assertAll(
"SMTP configuration",
() -> assertEquals("smtp.example.com", impl.getHost()),
() -> assertEquals(587, impl.getPort()),
() -> assertEquals("user@example.com", impl.getUsername()),
() -> assertEquals("password", impl.getPassword()),
() -> assertEquals("UTF-8", impl.getDefaultEncoding()),
() -> assertEquals("true", props.getProperty("mail.smtp.auth")),
() -> assertEquals("true", props.getProperty("mail.smtp.starttls.enable")));
}
}

View File

@ -1,18 +1,25 @@
package stirling.software.SPDF.controller.api; package stirling.software.SPDF.controller.api;
import static org.mockito.Mockito.*; import static org.mockito.ArgumentMatchers.any;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.mockito.Mockito.doNothing;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.mockito.Mockito.doThrow;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mail.MailSendException;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.multipart.MultipartFile;
import jakarta.mail.MessagingException; import jakarta.mail.MessagingException;
@ -20,7 +27,7 @@ import stirling.software.SPDF.config.security.mail.EmailService;
import stirling.software.SPDF.model.api.Email; import stirling.software.SPDF.model.api.Email;
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
public class EmailControllerTest { class EmailControllerTest {
private MockMvc mockMvc; private MockMvc mockMvc;
@ -28,59 +35,61 @@ public class EmailControllerTest {
@InjectMocks private EmailController emailController; @InjectMocks private EmailController emailController;
@Mock private MultipartFile fileInput;
@BeforeEach @BeforeEach
void setUp() { void setUp() {
// Set up the MockMvc instance for testing
mockMvc = MockMvcBuilders.standaloneSetup(emailController).build(); mockMvc = MockMvcBuilders.standaloneSetup(emailController).build();
} }
@Test @ParameterizedTest(name = "Case {index}: exception={0}, includeTo={1}")
void testSendEmailWithAttachmentSuccess() throws Exception { @MethodSource("emailParams")
// Create a mock Email object void shouldHandleEmailRequests(
Email email = new Email(); Exception serviceException,
email.setTo("test@example.com"); boolean includeTo,
email.setSubject("Test Email"); int expectedStatus,
email.setBody("This is a test email."); String expectedContent)
email.setFileInput(fileInput); throws Exception {
if (serviceException == null) {
doNothing().when(emailService).sendEmailWithAttachment(any(Email.class));
} else {
doThrow(serviceException).when(emailService).sendEmailWithAttachment(any(Email.class));
}
// Mock the service to not throw any exception var request =
doNothing().when(emailService).sendEmailWithAttachment(any(Email.class)); multipart("/api/v1/general/send-email")
.file("fileInput", "dummy-content".getBytes())
.param("subject", "Test Email")
.param("body", "This is a test email.");
// Perform the request and verify the response if (includeTo) {
mockMvc.perform( request = request.param("to", "test@example.com");
multipart("/api/v1/general/send-email") }
.file("fileInput", "dummy-content".getBytes())
.param("to", email.getTo()) mockMvc.perform(request)
.param("subject", email.getSubject()) .andExpect(status().is(expectedStatus))
.param("body", email.getBody())) .andExpect(content().string(expectedContent));
.andExpect(status().isOk())
.andExpect(content().string("Email sent successfully"));
} }
@Test static Stream<Arguments> emailParams() {
void testSendEmailWithAttachmentFailure() throws Exception { return Stream.of(
// Create a mock Email object // success case
Email email = new Email(); Arguments.of(null, true, 200, "Email sent successfully"),
email.setTo("test@example.com"); // generic messaging error
email.setSubject("Test Email"); Arguments.of(
email.setBody("This is a test email."); new MessagingException("Failed to send email"),
email.setFileInput(fileInput); true,
500,
// Mock the service to throw a MessagingException "Failed to send email: Failed to send email"),
doThrow(new MessagingException("Failed to send email")) // missing 'to' results in MailSendException
.when(emailService) Arguments.of(
.sendEmailWithAttachment(any(Email.class)); new MailSendException("Invalid Addresses"),
false,
// Perform the request and verify the response 500,
mockMvc.perform( "Invalid Addresses"),
multipart("/api/v1/general/send-email") // invalid email address formatting
.file("fileInput", "dummy-content".getBytes()) Arguments.of(
.param("to", email.getTo()) new MessagingException("Invalid Addresses"),
.param("subject", email.getSubject()) true,
.param("body", email.getBody())) 500,
.andExpect(status().isInternalServerError()) "Failed to send email: Invalid Addresses"));
.andExpect(content().string("Failed to send email: Failed to send email"));
} }
} }