5.3.3 account-email的测试代码
测试相关的Java代码位于src/test/java目录,相关的资源文件则位于src/test/resources目录。
该模块需要测试的只有一个AccountEmailService.sendMail()接口。为此,需要配置并启动一个测试使用的邮件服务器,然后提供对应的properties配置文件供Spring Framework载入以配置程序。准备就绪之后,调用该接口发送邮件,然后检查邮件是否发送正确。最后,关闭测试邮件服务器,见代码清单5-5。
代码清单5-5 AccountEmailServiceTest.java
package com.juvenxu.mvnbook.account.email;
import static junit.framework.Assert.assertEquals;
import javax.mail.Message;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.GreenMailUtil;
import com.icegreen.greenmail.util.ServerSetup;
public class AccountEmailServiceTest
{
private GreenMail greenMail;
@Before
public void startMailServer()
throws Exception
{
greenMail=new GreenMail(ServerSetup.SMTP);
greenMail.setUser("test@juvenxu.com","123456");
greenMail.start();
}
@Test
public void testSendMail()
throws Exception
{
ApplicationContext ctx=new ClassPathXmlApplicationContext("account-
email.xml");
AccountEmailService accountEmailService=(AccountEmailService)
ctx.getBean("accountEmailService");
String subject="Test Subject";
String htmlText="<h3>Test</h3>";
accountEmailService.sendMail("test2@juvenxu.com",subject,htmlText);
greenMail.waitForIncomingEmail(2000,1);
Message[]msgs=greenMail.getReceivedMessages();
assertEquals(1,msgs.length);
assertEquals(subject,msgs[0].getSubject());
assertEquals(htmlText,GreenMailUtil.getBody(msgs[0]).trim());
}
@After
public void stopMailServer()
throws Exception
{
greenMail.stop();
}
}
这里使用GreenMail作为测试邮件服务器,在startMailServer()中,基于SMTP协议初始化GreenMail,然后创建一个邮件账户并启动邮件服务,该服务默认会监听25端口。如果你的机器已经有程序使用该端口,请配置自定义的ServerSetup实例使用其他端口。startMailServer()方法使用了@before标注,表示该方法会先于测试方法(@test)之前执行。
对应于startMailServer(),该测试还有一个stopMailServer()方法,标注@After表示执行测试方法之后会调用该方法,停止GreenMail的邮件服务。
代码的重点在于使用了@Test标注的testSendMail()方法,该方法首先会根据classpath路径中的account-email.xml配置创建一个Spring Framework的ApplicationContext,然后从这个ctx中获取需要测试的id为accountEmailService的bean,并转换成AccountEmailService接口,针对接口测试是一个单元测试的最佳实践。得到了AccountEmailService之后,就能调用其sendMail()方法发送电子邮件。当然,这个时候不能忘了邮件服务器的配置,其位于src/test/resources/service.properties:
email.protocol=smtp
email.host=localhost
email.port=25
email.username=test@juvenxu.com
email.password=123456
email.auth=true
email.systemEmail=your-id@juvenxu.com
这段配置与之前GreenMail的配置对应,使用了smtp协议,使用本机的25端口,并有用户名、密码等认证配置。
回到测试方法中,邮件发送完毕后,再使用GreenMail进行检查。green-Mail.waitForIncomingEmail(2000,1)表示接收一封邮件,最多等待2秒。由于GreenMail服务完全基于内存,实际情况下基本不会超过2秒。随后的几行代码读取收到的邮件,检查邮件的数目以及第一封邮件的主题和内容。
这时,可以运行mvn clean test执行测试,Maven会编译主代码和测试代码,并执行测试,报告一个测试得以正确执行,构建成功。