【发布时间】:2020-03-11 22:49:07
【问题描述】:
我有这样的课:
public class StarshipEmailSender {
@Value("${email.from-email-address:}")
String from;
@Value("${email.from-name:}")
private String fromName;
@Value("${email.smtp.credentials-path:}")
String credentialPath;
@Value("${email.smtp.host:}")
String smtpHost;
@Value("${email.smtp.port:587}")
private int smtpPort;
@Autowired
private AClientFactory clientFactory;
private Properties sessionProperties;
private String smtpUsername = null;
private String smtpPassword = null;
public StarshipEmailSender() {
sessionProperties = new Properties();
sessionProperties.put("mail.transport.protocol", "smtp");
sessionProperties.put("mail.smtp.port", smtpPort);
sessionProperties.put("mail.smtp.starttls.enable", "true");
sessionProperties.put("mail.smtp.auth", "true");
}
public void sendMail(List<String> to, String subject, String contentType, String body)
throws MessagingException, UnsupportedEncodingException {
Session session = Session.getDefaultInstance(sessionProperties);
MimeMessage msg = contructMIMEMessage(session, to, subject, contentType, body);
Transport transport = session.getTransport();
try {
long start = System.currentTimeMillis();
transport.connect(smtpHost, smtpPort, smtpUsername, smtpPassword);
transport.sendMessage(msg, msg.getAllRecipients());
log.info("Email sent to : " + to + " in " + (System.currentTimeMillis()-start) + " millis");
} finally {
transport.close();
}
}
MimeMessage contructMIMEMessage(Session session, List<String> to, String subject, String contentType,
String body) throws UnsupportedEncodingException, MessagingException {
// code to construct a mime message ...
}
}
如何对sendMail() 方法进行单元测试?它有很多在方法中声明的变量,我无法从测试类中模拟它们:/我已经模拟了所有其他方法,因为它们更容易,但这种方法让我感到困惑。还是我以一种不允许单元测试灵活性的糟糕方式构建了这个类?
【问题讨论】:
标签: java unit-testing mocking mockito