我想使用it.ozimov.springboot.mail.service.EmailService
进行发送消息的单元测试。
https://github.com/ozimov/spring-boot-email-tools
这是我的MailService:
import com.google.common.collect.Lists;
import it.ozimov.springboot.mail.model.Email;
import it.ozimov.springboot.mail.model.defaultimpl.DefaultEmail;
import it.ozimov.springboot.mail.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.io.UnsupportedEncodingException;
@Service
public class MailService {
@Autowired
public EmailService emailService;
@Value("${spring.mail.username}")
private String username;
public void sendMail(String subject, String messageContent, String recipient)
throws UnsupportedEncodingException, AddressException {
final Email email = DefaultEmail.builder()
.from(new InternetAddress(username))
.to(Lists.newArrayList(new InternetAddress(recipient)))
.subject(subject)
.body(messageContent)
.encoding("UTF-8").build();
emailService.send(email);
}
}
我使用GreenMail进行测试,但它不起作用:
@RunWith(SpringJUnit4ClassRunner.class)
public class MailServiceTest {
private static final String USER_PASSWORD = "abcdef123";
private static final String USER_NAME = "hascode";
private static final String EMAIL_USER_ADDRESS = "hascode@localhost";
private static final String EMAIL_TO = "someone@localhost.com";
private static final String EMAIL_SUBJECT = "Test E-Mail";
private static final String EMAIL_TEXT = "This is a test e-mail.";
private static final String LOCALHOST = "127.0.0.1";
private GreenMail mailServer;
@InjectMocks
private MailService mailService = new MailService();
@Mock
private EmailService emailService;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mailServer = new GreenMail(ServerSetupTest.SMTP);
mailServer.start();
mailServer.setUser(EMAIL_USER_ADDRESS, USER_NAME, USER_PASSWORD);
}
@After
public void tearDown() {
mailServer.stop();
}
@Test
public void getMails() throws IOException, MessagingException,
UserException, InterruptedException {
String subject = "Some subject";
String body = "Some contents.";
String recipient = "test@test.com";
ReflectionTestUtils.setField(mailService, "username", "bla");
mailService.sendMail(subject, body, recipient);
MimeMessage[] messages = mailServer.getReceivedMessages();
assertNotNull(messages);
assertEquals(1, messages.length);
MimeMessage m = messages[0];
assertEquals(EMAIL_SUBJECT, m.getSubject());
assertTrue(String.valueOf(m.getContent()).contains(EMAIL_TEXT));
assertEquals(EMAIL_TO, m.getFrom()[0].toString());
}
}
结果我得到了这个:
java.lang.AssertionError:
Expected :1
Actual :0
有人可能知道我做错了什么?因为MailService在控制器中工作(它发送电子邮件),但测试不起作用。
答案 0 :(得分:0)
问题在于您使用模拟EmailService的单元测试与GreenMail一起使用,旨在支持集成测试。
如果您查看已使用的库,您将看到差异。例如。看看this context-based test