MIMEMessage和MIMEMessage模拟测试用例失败,并在EmailUtil上声明错误

时间:2018-07-01 11:21:46

标签: junit4 powermock easymock

我要实现的目标-我为Spring MVC应用程序编写的EmailUtil的简单单元测试。 我陷入困境的地方-尽管我已经嘲笑了MIMEmessage和JavaMailSender,但是测试用例在MimeMessageHelper.set ****方法中失败了。

对此表示感谢,因为我尝试了几种不同的方法,即使最近使用PowerMock也没有成功。

EmailUtil.Java

import java.util.List;

import javax.activation.DataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.dashboard.domain.Attachment;
import com.dashboard.domain.Email;

public class EmailUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(EmailUtil.class
            .getName());

    /**
     * Private constructor to make sure that no one creating instance
     */
    private EmailUtil() {

    }

    /**
     * Functionality to send the mail. This method used the mail sender
     * configuration from spring-context file.
     * 
     * @param email
     * @param mailSender
     * @throws MessagingException
     */
    public static void sendEmail(JavaMailSender mailSender, Email email)
            throws MessagingException {

        LOGGER.info("Start of the method: sendEmail");
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        // use the true flag to indicate you need a multi part message
        boolean hasAttachments = email.getAttachments() != null
                && !email.getAttachments().isEmpty();
        LOGGER.info(" mimeMessage - {} ",mimeMessage);
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,
                hasAttachments);
        LOGGER.info(" MimeMessageHelper - {} ",helper);
        helper.setTo(email.getTo());
        helper.setFrom(email.getFrom());
        helper.setCc(email.getCc());
        helper.setSubject(email.getSubject());
        helper.setText(email.getText(), true);

        List<Attachment> attachments = email.getAttachments();
        if (!attachments.isEmpty()) {
            for (Attachment attachment : attachments) {
                String filename = attachment.getFilename();
                DataSource dataSource = new ByteArrayDataSource(
                        attachment.getData(), attachment.getMimeType());
                if (attachment.isInline()) {
                    helper.addInline(filename, dataSource);
                } else {
                    helper.addAttachment(filename, dataSource);
                }
            }
        }
        mailSender.send(mimeMessage);
        LOGGER.info("End of the method: sendEmail");
    }


}

EmailUtilTest.Java

import static org.easymock.EasyMock.expect;

import javax.mail.Address;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import org.easymock.EasyMock;
import org.easymock.Mock;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.dashboard.domain.ApplicationConstant;
import com.dashboard.domain.Email;

/**
 * PowerMockDemo
 * @author s.arumugam
 *
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest(EmailUtil.class)
public class EmailUtilTest {

    Email email = new Email();

    @Mock
    JavaMailSender javaMailSender;

    @Mock
    MimeMessage mimeMessage;

    @Mock
    MimeMessageHelper mimeMessageHelper;

    @Before
    public void initList() {
        email.setFrom(ApplicationConstant.DEFAULT_MAIL_ID.getValue());
        email.setSubject("Subject");
        email.setTo("to.email@userdomain.com");
        email.setCc("admin@dashboard.com");
        email.setText("Body of the email"); 
    }

    @Test
    public void sendEmailTest() throws Exception{      
        mimeMessageHelper.setSubject(email.getSubject());
        mimeMessageHelper.setFrom(new InternetAddress(email.getFrom(), true));
        mimeMessageHelper.setCc(new InternetAddress(email.getCc()[0], true));
        mimeMessageHelper.setTo(new InternetAddress(email.getTo()[0], true));
        mimeMessageHelper.setText(email.getText());
        expect(javaMailSender.createMimeMessage()).andReturn(mimeMessage);
        Address sendTo[]={new InternetAddress(email.getTo()[0])};
        mimeMessage.setRecipients(RecipientType.TO,sendTo);
        EasyMock.expectLastCall().times(1);
        EasyMock.replay(mimeMessage);
        EasyMock.replay(javaMailSender);
        EmailUtil.sendEmail(javaMailSender, email);
        EasyMock.verify(mimeMessage);
        EasyMock.verify(javaMailSender);
    }

}

错误消息:

java.lang.AssertionError:    Unexpected method call MimeMessage.setRecipients(To, [to.email@userdomain.com]):
    MimeMessage.setRecipients(To, [to.email@userdomain.com]): expected: 1, actual: 0    at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)    at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94)    at org.easymock.internal.ClassProxyFactory$MockMethodInterceptor.intercept(ClassProxyFactory.java:97)   at $javax.mail.internet.MimeMessage$$EnhancerByCGLIB$$a6025b60.setRecipients(<generated>)   at org.springframework.mail.javamail.MimeMessageHelper.setTo(MimeMessageHelper.java:581)    at org.springframework.mail.javamail.MimeMessageHelper.setTo(MimeMessageHelper.java:595)    at com.dashboard.util.EmailUtil.sendEmail(EmailUtil.java:50)

2 个答案:

答案 0 :(得分:0)

哦..我设法解决了这个问题..纯粹是通过随机试验和错误..!也就是说,我需要深入了解这些模拟工具的工作原理。.下面的工作测试用例,希望有人可以找到测试用例的完整工作示例;

@RunWith(EasyMockRunner.class)
public class EmailUtilTest extends EasyMockSupport{

    @Mock
    JavaMailSender mailSender;

    @Mock
    MimeMessage mimeMessage;

    @Test
    public void testSendEmail() throws MessagingException{
        Email email = new Email();
        email.setFrom("from.email@dashboard.com");
        email.setSubject("Subject");
        email.setTo("to.email@userdomain.com");
        email.setCc("admin@dashboard.com");
        email.setText("Body of the email");
        EasyMock.expect(mailSender.createMimeMessage()).andReturn(mimeMessage);
        mailSender.send(mimeMessage);
        EasyMock.expectLastCall();
        EasyMock.replay(mailSender);
        EmailUtil.sendEmail(mailSender, email);
        EasyMock.verify(mailSender);
    }

}

答案 1 :(得分:0)

得到java.lang.AssertionError的原因是因为EasyMock使用equals()方法比较传递给方法的参数,而不能使用equals()比较数组。

Address toAddress = new InternetAddress("a@b.com");
Address[] a1 = { toAddress };
Address[] a2 = { toAddress };
if (a1.equals(a2)) { // this will be false
    // so this won't happen
}

非常感谢,EasyMock为我们提供了几种不同的参数匹配器。在这种情况下,我们应该使用EasyMock.aryEq()。因此,为了模拟对setRecipients()方法的调用:

mimeMessage.setRecipients(EasyMock.eq(RecipientType.TO) , EasyMock.aryEq(sendTo));

我不确定在不更改EmailUtil类的情况下接受的答案如何工作。