-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathMailServiceTest.java
More file actions
598 lines (477 loc) · 24 KB
/
Copy pathMailServiceTest.java
File metadata and controls
598 lines (477 loc) · 24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
package com.digitalsanctuary.spring.user.mail;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import jakarta.mail.internet.MimeMessage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.test.util.ReflectionTestUtils;
import org.thymeleaf.context.Context;
/**
* Comprehensive unit tests for MailService that verify actual business logic
* for email sending including async behavior, retry mechanism, and template processing.
*/
@ExtendWith(MockitoExtension.class)
@DisplayName("MailService Tests")
class MailServiceTest {
@Mock
private JavaMailSender mailSender;
@Mock
private ObjectProvider<JavaMailSender> mailSenderProvider;
@Mock
private MailContentBuilder mailContentBuilder;
@Mock
private MimeMessage mimeMessage;
private MailService mailService;
private static final String FROM_ADDRESS = "noreply@example.com";
private static final String TO_ADDRESS = "user@example.com";
private static final String SUBJECT = "Test Subject";
@BeforeEach
void setUp() {
// Provider returns the mock mailSender by default.
lenient().when(mailSenderProvider.getIfAvailable()).thenReturn(mailSender);
mailService = new MailService(mailSenderProvider, mailContentBuilder);
mailService.init(); // simulate @PostConstruct — caches the resolved sender
ReflectionTestUtils.setField(mailService, "fromAddress", FROM_ADDRESS);
// Setup default mock behavior
lenient().when(mailSender.createMimeMessage()).thenReturn(mimeMessage);
}
@Nested
@DisplayName("Simple Message Tests")
class SimpleMessageTests {
@Test
@DisplayName("Should send simple message with correct parameters")
void shouldSendSimpleMessageWithCorrectParameters() throws Exception {
// Given
String messageText = "This is a test email";
ArgumentCaptor<MimeMessagePreparator> preparatorCaptor =
ArgumentCaptor.forClass(MimeMessagePreparator.class);
// When
mailService.sendSimpleMessage(TO_ADDRESS, SUBJECT, messageText);
// Then
verify(mailSender).send(preparatorCaptor.capture());
// Verify the message preparator sets correct values
MimeMessagePreparator preparator = preparatorCaptor.getValue();
assertThat(preparator).isNotNull();
// Execute the preparator to verify its behavior
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
preparator.prepare(mimeMessage);
// We can't directly verify MimeMessageHelper calls, but we can verify
// that the preparator doesn't throw exceptions when executed
}
@Test
@DisplayName("Should handle null recipient gracefully")
void shouldHandleNullRecipient() {
// Given
String messageText = "Test message";
// When/Then - The async nature means exceptions might be swallowed
// In real implementation, this would be handled by Spring's async error handler
mailService.sendSimpleMessage(null, SUBJECT, messageText);
// Verify send was attempted
verify(mailSender).send(any(MimeMessagePreparator.class));
}
@Test
@DisplayName("Should handle empty subject and text")
void shouldHandleEmptySubjectAndText() {
// When
mailService.sendSimpleMessage(TO_ADDRESS, "", "");
// Then
verify(mailSender).send(any(MimeMessagePreparator.class));
}
@Test
@DisplayName("Should handle very long message text")
void shouldHandleVeryLongMessageText() {
// Given
String longText = "a".repeat(10000);
// When
mailService.sendSimpleMessage(TO_ADDRESS, SUBJECT, longText);
// Then
verify(mailSender).send(any(MimeMessagePreparator.class));
}
@Test
@DisplayName("Should set HTML flag to true for message text")
void shouldSetHtmlFlagForMessageText() throws Exception {
// Given
String htmlText = "<html><body><h1>Test</h1></body></html>";
ArgumentCaptor<MimeMessagePreparator> preparatorCaptor =
ArgumentCaptor.forClass(MimeMessagePreparator.class);
// When
mailService.sendSimpleMessage(TO_ADDRESS, SUBJECT, htmlText);
// Then
verify(mailSender).send(preparatorCaptor.capture());
// The setText method is called with true for HTML
MimeMessagePreparator preparator = preparatorCaptor.getValue();
preparator.prepare(mimeMessage);
}
}
@Nested
@DisplayName("Template Message Tests")
class TemplateMessageTests {
@Test
@DisplayName("Should send template message with correct parameters")
void shouldSendTemplateMessageWithCorrectParameters() throws Exception {
// Given
Map<String, Object> variables = new HashMap<>();
variables.put("username", "John Doe");
variables.put("link", "https://example.com/verify");
String templatePath = "email/verification";
String renderedContent = "<html><body>Hello John Doe</body></html>";
ArgumentCaptor<MimeMessagePreparator> preparatorCaptor =
ArgumentCaptor.forClass(MimeMessagePreparator.class);
// When
mailService.sendTemplateMessage(TO_ADDRESS, SUBJECT, variables, templatePath);
// Then
verify(mailSender).send(preparatorCaptor.capture());
// Execute preparator to trigger template building
when(mailContentBuilder.build(eq(templatePath), any(Context.class)))
.thenReturn(renderedContent);
MimeMessagePreparator preparator = preparatorCaptor.getValue();
preparator.prepare(mimeMessage);
// Now verify template builder was called
verify(mailContentBuilder).build(eq(templatePath), any(Context.class));
}
@Test
@DisplayName("Should pass variables correctly to template builder")
void shouldPassVariablesToTemplateBuilder() throws Exception {
// Given
Map<String, Object> variables = new HashMap<>();
variables.put("name", "Jane");
variables.put("code", "12345");
variables.put("expiry", "24 hours");
String templatePath = "email/password-reset";
ArgumentCaptor<MimeMessagePreparator> preparatorCaptor =
ArgumentCaptor.forClass(MimeMessagePreparator.class);
// When
mailService.sendTemplateMessage(TO_ADDRESS, SUBJECT, variables, templatePath);
// Then
verify(mailSender).send(preparatorCaptor.capture());
// Setup mock and execute preparator
ArgumentCaptor<Context> contextCaptor = ArgumentCaptor.forClass(Context.class);
when(mailContentBuilder.build(eq(templatePath), contextCaptor.capture()))
.thenReturn("<html>Reset password</html>");
MimeMessagePreparator preparator = preparatorCaptor.getValue();
preparator.prepare(mimeMessage);
// Verify context was passed with variables
Context capturedContext = contextCaptor.getValue();
assertThat(capturedContext).isNotNull();
verify(mailContentBuilder).build(eq(templatePath), any(Context.class));
}
@Test
@DisplayName("Should handle empty variables map")
void shouldHandleEmptyVariablesMap() throws Exception {
// Given
Map<String, Object> emptyVariables = new HashMap<>();
String templatePath = "email/simple";
ArgumentCaptor<MimeMessagePreparator> preparatorCaptor =
ArgumentCaptor.forClass(MimeMessagePreparator.class);
// When
mailService.sendTemplateMessage(TO_ADDRESS, SUBJECT, emptyVariables, templatePath);
// Then
verify(mailSender).send(preparatorCaptor.capture());
// Execute preparator
when(mailContentBuilder.build(anyString(), any(Context.class)))
.thenReturn("<html>Simple email</html>");
preparatorCaptor.getValue().prepare(mimeMessage);
verify(mailContentBuilder).build(eq(templatePath), any(Context.class));
}
@Test
@DisplayName("Should handle null variables map")
void shouldHandleNullVariablesMap() throws Exception {
// Given
String templatePath = "email/notification";
ArgumentCaptor<MimeMessagePreparator> preparatorCaptor =
ArgumentCaptor.forClass(MimeMessagePreparator.class);
// When
mailService.sendTemplateMessage(TO_ADDRESS, SUBJECT, null, templatePath);
// Then
verify(mailSender).send(preparatorCaptor.capture());
// Execute preparator
when(mailContentBuilder.build(anyString(), any(Context.class)))
.thenReturn("<html>Notification</html>");
preparatorCaptor.getValue().prepare(mimeMessage);
verify(mailContentBuilder).build(eq(templatePath), any(Context.class));
}
@Test
@DisplayName("Should handle complex nested variables")
void shouldHandleComplexNestedVariables() throws Exception {
// Given
Map<String, Object> variables = new HashMap<>();
Map<String, String> userInfo = new HashMap<>();
userInfo.put("firstName", "John");
userInfo.put("lastName", "Doe");
variables.put("user", userInfo);
variables.put("items", new String[]{"item1", "item2", "item3"});
String templatePath = "email/complex";
ArgumentCaptor<MimeMessagePreparator> preparatorCaptor =
ArgumentCaptor.forClass(MimeMessagePreparator.class);
// When
mailService.sendTemplateMessage(TO_ADDRESS, SUBJECT, variables, templatePath);
// Then
verify(mailSender).send(preparatorCaptor.capture());
// Execute preparator
when(mailContentBuilder.build(eq(templatePath), any(Context.class)))
.thenReturn("<html>Complex email</html>");
preparatorCaptor.getValue().prepare(mimeMessage);
verify(mailContentBuilder).build(eq(templatePath), any(Context.class));
}
}
@Nested
@DisplayName("Retry and Recovery Tests")
class RetryAndRecoveryTests {
@Test
@DisplayName("Should attempt to send despite MailException (retry handled by Spring)")
void shouldAttemptToSendDespiteMailException() {
// Given
MailSendException exception = new MailSendException("Connection failed");
// Note: @Retryable doesn't work in unit tests without Spring context
// In production, this would retry 3 times with backoff
doThrow(exception).when(mailSender).send(any(MimeMessagePreparator.class));
// When/Then - Exception is thrown but @Async would handle it
try {
mailService.sendSimpleMessage(TO_ADDRESS, SUBJECT, "Test message");
} catch (MailSendException e) {
// Expected in unit test context
assertThat(e.getMessage()).isEqualTo("Connection failed");
}
// Verify send was attempted
verify(mailSender).send(any(MimeMessagePreparator.class));
}
@Test
@DisplayName("Recovery method should log error for simple message")
void recoveryMethodShouldLogErrorForSimpleMessage() {
// Given
MailSendException exception = new MailSendException("SMTP server down");
String text = "Important message";
// When - Call recovery method directly since we can't trigger retry in unit test
mailService.recoverSendSimpleMessage(exception, TO_ADDRESS, SUBJECT, text);
// Then - Method completes without throwing exception (logs error)
// In a real test with logging verification, we'd check the log output
}
@Test
@DisplayName("Recovery method should log error for template message")
void recoveryMethodShouldLogErrorForTemplateMessage() {
// Given
MailSendException exception = new MailSendException("Template processing failed");
Map<String, Object> variables = new HashMap<>();
variables.put("key", "value");
String templatePath = "email/test";
// When - Call recovery method directly
mailService.recoverSendTemplateMessage(exception, TO_ADDRESS, SUBJECT, variables, templatePath);
// Then - Method completes without throwing exception (logs error)
}
@Test
@DisplayName("Should handle permanent MailException gracefully")
void shouldHandlePermanentMailException() {
// Given
MailSendException permanentException = new MailSendException("Invalid recipient");
doThrow(permanentException).when(mailSender).send(any(MimeMessagePreparator.class));
// When/Then
try {
mailService.sendSimpleMessage("invalid-email", SUBJECT, "Test");
} catch (MailSendException e) {
// Expected in unit test - in production @Async would handle this
assertThat(e.getMessage()).isEqualTo("Invalid recipient");
}
// Verify send was attempted
verify(mailSender).send(any(MimeMessagePreparator.class));
}
}
@Nested
@DisplayName("Async Behavior Tests")
class AsyncBehaviorTests {
@Test
@DisplayName("Should execute sendSimpleMessage asynchronously")
void shouldExecuteSendSimpleMessageAsynchronously() {
// Given
String message = "Async test message";
// When
mailService.sendSimpleMessage(TO_ADDRESS, SUBJECT, message);
// Then - Method returns immediately (in real async context)
verify(mailSender).send(any(MimeMessagePreparator.class));
}
@Test
@DisplayName("Should execute sendTemplateMessage asynchronously")
void shouldExecuteSendTemplateMessageAsynchronously() throws Exception {
// Given
Map<String, Object> variables = new HashMap<>();
variables.put("async", true);
String templatePath = "email/async";
ArgumentCaptor<MimeMessagePreparator> preparatorCaptor =
ArgumentCaptor.forClass(MimeMessagePreparator.class);
// When
mailService.sendTemplateMessage(TO_ADDRESS, SUBJECT, variables, templatePath);
// Then - Method returns immediately (in real async context)
verify(mailSender).send(preparatorCaptor.capture());
// Execute preparator to verify template builder interaction
when(mailContentBuilder.build(anyString(), any(Context.class)))
.thenReturn("<html>Async email</html>");
preparatorCaptor.getValue().prepare(mimeMessage);
verify(mailContentBuilder).build(eq(templatePath), any(Context.class));
}
@Test
@DisplayName("Multiple async calls should not block each other")
void multipleAsyncCallsShouldNotBlock() {
// When - Send multiple simple emails (not template emails)
for (int i = 0; i < 5; i++) {
mailService.sendSimpleMessage("user" + i + "@example.com", "Subject " + i, "Message " + i);
}
// Then - All calls complete without blocking
verify(mailSender, times(5)).send(any(MimeMessagePreparator.class));
}
}
@Nested
@DisplayName("Edge Cases and Error Handling Tests")
class EdgeCasesTests {
@Test
@DisplayName("Should handle special characters in email addresses")
void shouldHandleSpecialCharactersInEmail() {
// Given
String specialEmail = "user+test@sub.example.com";
// When
mailService.sendSimpleMessage(specialEmail, SUBJECT, "Test");
// Then
verify(mailSender).send(any(MimeMessagePreparator.class));
}
@Test
@DisplayName("Should handle international characters in subject and content")
void shouldHandleInternationalCharacters() {
// Given
String intlSubject = "测试邮件 - Test Email - Тестовое письмо";
String intlContent = "你好世界 - Hello World - Привет мир";
// When
mailService.sendSimpleMessage(TO_ADDRESS, intlSubject, intlContent);
// Then
verify(mailSender).send(any(MimeMessagePreparator.class));
}
@Test
@DisplayName("Should handle multiple recipients in TO field")
void shouldHandleMultipleRecipients() {
// Given
String multipleRecipients = "user1@example.com,user2@example.com";
// When
mailService.sendSimpleMessage(multipleRecipients, SUBJECT, "Broadcast message");
// Then
verify(mailSender).send(any(MimeMessagePreparator.class));
}
@Test
@DisplayName("Should handle template builder returning null")
void shouldHandleTemplateBuilderReturningNull() throws Exception {
// Given
ArgumentCaptor<MimeMessagePreparator> preparatorCaptor =
ArgumentCaptor.forClass(MimeMessagePreparator.class);
// When
mailService.sendTemplateMessage(TO_ADDRESS, SUBJECT, new HashMap<>(), "email/null");
// Then - Should still attempt to send
verify(mailSender).send(preparatorCaptor.capture());
// Execute preparator with null return from builder - this will throw
when(mailContentBuilder.build(anyString(), any(Context.class)))
.thenReturn(null);
// MimeMessageHelper.setText throws IllegalArgumentException for null text
assertThatThrownBy(() -> preparatorCaptor.getValue().prepare(mimeMessage))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Text must not be null");
verify(mailContentBuilder).build(eq("email/null"), any(Context.class));
}
@Test
@DisplayName("Should handle template builder throwing exception")
void shouldHandleTemplateBuilderException() throws Exception {
// Given
ArgumentCaptor<MimeMessagePreparator> preparatorCaptor =
ArgumentCaptor.forClass(MimeMessagePreparator.class);
// When
mailService.sendTemplateMessage(TO_ADDRESS, SUBJECT, new HashMap<>(), "email/missing");
// Then - Send is called
verify(mailSender).send(preparatorCaptor.capture());
// Execute preparator - exception happens during preparation
when(mailContentBuilder.build(anyString(), any(Context.class)))
.thenThrow(new RuntimeException("Template not found"));
assertThatThrownBy(() -> preparatorCaptor.getValue().prepare(mimeMessage))
.isInstanceOf(RuntimeException.class)
.hasMessage("Template not found");
}
}
@Nested
@DisplayName("Missing JavaMailSender Tests")
class MissingMailSenderTests {
private MailService unconfiguredMailService;
@BeforeEach
void setUpUnconfigured() {
// Separate service instance where the sender is absent from startup.
when(mailSenderProvider.getIfAvailable()).thenReturn(null);
unconfiguredMailService = new MailService(mailSenderProvider, mailContentBuilder);
unconfiguredMailService.init();
ReflectionTestUtils.setField(unconfiguredMailService, "fromAddress", FROM_ADDRESS);
}
@Test
@DisplayName("sendSimpleMessage should no-op when JavaMailSender is not configured")
void sendSimpleMessageNoOpsWhenSenderMissing() {
unconfiguredMailService.sendSimpleMessage(TO_ADDRESS, SUBJECT, "Body");
verify(mailSender, never()).send(any(MimeMessagePreparator.class));
}
@Test
@DisplayName("sendTemplateMessage should no-op when JavaMailSender is not configured")
void sendTemplateMessageNoOpsWhenSenderMissing() {
unconfiguredMailService.sendTemplateMessage(TO_ADDRESS, SUBJECT, new HashMap<>(), "email/test");
verify(mailSender, never()).send(any(MimeMessagePreparator.class));
verify(mailContentBuilder, never()).build(anyString(), any(Context.class));
}
}
@Nested
@DisplayName("Integration with MimeMessageHelper Tests")
class MimeMessageHelperIntegrationTests {
@Test
@DisplayName("Should properly configure MimeMessageHelper for simple message")
void shouldConfigureMimeMessageHelperForSimpleMessage() throws Exception {
// Given
ArgumentCaptor<MimeMessagePreparator> preparatorCaptor =
ArgumentCaptor.forClass(MimeMessagePreparator.class);
String messageText = "Test content";
// When
mailService.sendSimpleMessage(TO_ADDRESS, SUBJECT, messageText);
// Then
verify(mailSender).send(preparatorCaptor.capture());
// Verify preparator configures message correctly
MimeMessagePreparator preparator = preparatorCaptor.getValue();
assertThat(preparator).isNotNull();
// Execute preparator - it should not throw any exceptions
preparator.prepare(mimeMessage);
}
@Test
@DisplayName("Should properly configure MimeMessageHelper for template message")
void shouldConfigureMimeMessageHelperForTemplateMessage() throws Exception {
// Given
Map<String, Object> variables = new HashMap<>();
variables.put("test", "value");
String renderedHtml = "<html><body>Rendered content</body></html>";
when(mailContentBuilder.build(anyString(), any(Context.class)))
.thenReturn(renderedHtml);
ArgumentCaptor<MimeMessagePreparator> preparatorCaptor =
ArgumentCaptor.forClass(MimeMessagePreparator.class);
// When
mailService.sendTemplateMessage(TO_ADDRESS, SUBJECT, variables, "email/test");
// Then
verify(mailSender).send(preparatorCaptor.capture());
// Execute preparator - it should not throw any exceptions
MimeMessagePreparator preparator = preparatorCaptor.getValue();
preparator.prepare(mimeMessage);
}
}
}