在Spring Boot中,可以使用Mockito來模擬郵件發送功能,并使用JUnit來編寫測試用例。下面是一個簡單的示例:
首先,在Spring Boot項目中添加相關依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.11.0</version>
<scope>test</scope>
</dependency>
然后編寫一個郵件發送服務:
@Service
public class EmailService {
@Autowired
private JavaMailSender javaMailSender;
public void sendEmail(String to, String subject, String body) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(body);
javaMailSender.send(message);
}
}
接下來編寫一個測試用例:
@RunWith(MockitoJUnitRunner.class)
public class EmailServiceTest {
@Mock
private JavaMailSender javaMailSender;
@InjectMocks
private EmailService emailService;
@Test
public void testSendEmail() {
emailService.sendEmail("test@example.com", "Test Subject", "Test Body");
ArgumentCaptor<SimpleMailMessage> captor = ArgumentCaptor.forClass(SimpleMailMessage.class);
verify(javaMailSender).send(captor.capture());
SimpleMailMessage message = captor.getValue();
assertEquals("test@example.com", message.getTo()[0]);
assertEquals("Test Subject", message.getSubject());
assertEquals("Test Body", message.getText());
}
}
在上面的測試用例中,我們使用Mockito來模擬JavaMailSender并驗證發送郵件的行為。通過ArgumentCaptor來捕獲發送的郵件內容,并進行斷言驗證。
這樣就可以使用JUnit來測試郵件發送功能了。