我正在尝试验证我在测试方法中创建的对象和实际对象是否在所有字段中具有相同的值。我已经使用Matchers.refEq()来验证这一点。在我的代码中,两个对象的实际引用正在得到验证,而不是字段值,而不是文档对 Matchers.refEq() 所说的。
下面的测试用例有什么问题?
@Test
public void sendEmailMsgTest() throws MessagingException{
PowerMockito.mockStatic(Transport.class);
PowerMockito.doNothing().when(Transport.class);
Transport.send(Matchers.any(MimeMessage.class));
Properties systemProperties = System.getProperties();
Session session = Session.getDefaultInstance(systemProperties);
session.setDebug(debug);
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress(sendFrom));
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(
validEmailAddress));
mimeMessage.setSubject("HTML/CSS grade report");
mimeMessage.setSentDate(new Date());
final BodyPart textBodyPart = new MimeBodyPart();
textBodyPart
.setText("Here is your score card for the HTML/CSS assessment");
final BodyPart fileBodyPart = new MimeBodyPart();
final DataSource source = new FileDataSource(outputFile);
fileBodyPart.setDataHandler(new DataHandler(source));
fileBodyPart.setFileName(new File(outputFile).getName());
final Multipart multipart = new MimeMultipart();
multipart.addBodyPart(textBodyPart);
multipart.addBodyPart(fileBodyPart);
mimeMessage.setContent(multipart);
WriteGradeReportUtil.emailGrade(validEmailAddress, outputFile);
Mockito.verify(Transport.class);
Transport.send(Matchers.refEq(mimeMessage));
}
我正在尝试测试的方法:
static void emailGrade(){
//Some code
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(sendFrom));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
sendTo));
message.setSubject("HTML/CSS grade report");
message.setSentDate(new Date());
final BodyPart textBodyPart = new MimeBodyPart();
textBodyPart
.setText("Here is your score card for the HTML/CSS assessment");
final BodyPart fileBodyPart = new MimeBodyPart();
final DataSource source = new FileDataSource(outputFile);
fileBodyPart.setDataHandler(new DataHandler(source));
fileBodyPart.setFileName(new File(outputFile).getName());
final Multipart multipart = new MimeMultipart();
multipart.addBodyPart(textBodyPart);
multipart.addBodyPart(fileBodyPart);
message.setContent(multipart);
Transport.send(message);
}
Mockito 1.x内部使用Hamcrest匹配器,内部匹配器使用Apache公共org.mockito.internal.matchers.apachecommons.EqualsBuilder#reflectionEquals(java.lang.Object, java.lang.Object, java.lang.String[])
。Mockito 2.x直接使用Apache共享资源org.mockito.internal.matchers.apachecommons.EqualsBuilder#reflectionEquals(java.lang.Object, java.lang.Object, java.lang.String[])
因此,如果此调用显示对象不相等,则可能您的某个字段根本不相等。
另请注意,Mockito javadoc警告您:<b>Warning</b> The equality check is shallow!
也许这些字段也没有实现equals
,因此它们不能相等。
除了这个答案的范围之外,我还想对代码片段发表评论。很难理解,然后重构。嘲笑者的座右铭之一是不要嘲笑你不拥有的类型。相反,您应该使用模拟邮件服务器 - 那里有很多 - 并将邮件直接发送到那里。