架构如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20181126191605600.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzIzNDQ1MQ==,size_16,color_FFFFFF,t_70)
需要引用的包:
freemarker.jar
FreemarkerTemplateEngine.java——基础类
package com.freemarker;
import java.io.File;
import java.io.StringWriter;
import java.util.Locale;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
public class FreemarkerTemplateEngine {
private static final String DEFAULT_TEMPLATE = "conf/reportTemplate.html";
public String getTemplatePath() {
return "";
}
public String run(Map context) throws Exception{
return executeFreemarker(context);
}
private String executeFreemarker(Map context)throws Exception{
String content="";
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(
new File(getTemplatePath()));
cfg.setEncoding(Locale.CHINA, "UTF-8");
cfg.setObjectWrapper(new DefaultObjectWrapper());
cfg.setCacheStorage(new freemarker.cache.MruCacheStorage(20, 250));
Template temp = cfg.getTemplate(getTemplate());
StringWriter out = new StringWriter();
temp.process(context, out);
//System.out.print(out.toString());
return out.toString();
}
public String getTemplate() {
// TODO Auto-generated method stub
return DEFAULT_TEMPLATE;
}
}
MailUtil.java——发送邮件的类
package com.freemarker;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailUtil {
static int port = 25;
static String server = "smtp.126.com";
static String from = "发件人姓名";
static String user = "发件人邮箱@126.com";
static String password = "发件人邮箱授权码";
public static void sendEmail(String email, String subject, String body) throws UnsupportedEncodingException {
try {
Properties props = new Properties();
props.put("mail.smtp.host", server);
props.put("mail.smtp.port", String.valueOf(port));
props.put("mail.smtp.auth", "true");
Transport transport = null;
Session session = Session.getDefaultInstance(props, null);
transport = session.getTransport("smtp");
transport.connect(server, user, password);
MimeMessage msg = new MimeMessage(session);
msg.setSentDate(new Date());
InternetAddress fromAddress = new InternetAddress(user, from, "UTF-8");
msg.setFrom(fromAddress);
String emailList[] = email.split(",");
InternetAddress[] toAddress = new InternetAddress[emailList.length];
for (int i = 0; i < emailList.length; i++) {
toAddress[i] = new InternetAddress(emailList[i]);
}
// msg.setRecipients(Message.RecipientType.TO, toAddress);
msg.addRecipients(Message.RecipientType.TO, toAddress);
msg.setSubject(subject, "UTF-8");
msg.setContent(body, "text/html;charset=utf-8");
msg.saveChanges();
transport.sendMessage(msg, msg.getAllRecipients());
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public static void main(String args[]) throws UnsupportedEncodingException {
MailUtil.sendEmail("发件人邮箱@126.com", "ceshi", "ce");
}
}
WebTestListener.java——监听类
package com.freemarker;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
import com.webtest.utils.Log;
import com.webtest.utils.ReadProperties;
//监听器
public class WebTestListener extends TestListenerAdapter {
FreemarkerTemplateEngine ft=new FreemarkerTemplateEngine();
public WebTestListener() {
super();
}
private String writeResultToMailTemplate()
{
ITestNGMethod method[]=this.getAllTestMethods();
List failedList=this.getFailedTests();
List passedList=this.getPassedTests();
List failedList1=new ArrayList();
List passedList1=new ArrayList();
for(int j=0;j<failedList.size();j++)
{
ITestResult tr=(ITestResult) failedList.get(j);
for(int i=0;i<method.length;i++)
{
if(tr.getMethod().getMethodName().equals(method[i].getMethodName()))
{
if(method[i].getDescription()!=null)
{
tr.setAttribute("name", method[i].getDescription());
}
else
{
tr.setAttribute("name", "");
}
break;
}
}
failedList1.add(tr);
}
for(int j=0;j<passedList.size();j++)
{
ITestResult tr=(ITestResult) passedList.get(j);
for(int i=0;i<method.length;i++)
{
if(tr.getMethod().getMethodName().equals(method[i].getMethodName()))
{
if(method[i].getDescription()!=null)
{
tr.setAttribute("name", method[i].getDescription());
}
else
{
tr.setAttribute("name", "");
}
break;
}
}
passedList1.add(tr);
}
Map context=new HashMap();
context.put("date", new Date());
context.put("failedList",failedList);
context.put("passedList",passedList1);
context.put("casesize",passedList.size()+failedList.size());
context.put("failcasesize",failedList.size());
try {
String content=ft.run(context);
return content;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
public void onFinish(ITestContext testContext){
// TODO Auto-generated method stub
super.onFinish(testContext);
if(System.getProperty("os.name").contains("dow"))
{
//return;
}
try {
if(ReadProperties.getPropertyValue("enable_email").equals("true"))
{
String emailContent=this.writeResultToMailTemplate();
String emailTitle=ReadProperties.getPropertyValue("mail_title")+"----"+this.getTime();
String toMail=ReadProperties.getPropertyValue("to_mail");
try {
if(this.getFailedTests()!=null&&this.getFailedTests().size()>0)
{
MailUtil.sendEmail(toMail,emailTitle, emailContent);
Log.info("email send to "+toMail+" success");
}else
{
MailUtil.sendEmail(ReadProperties.getPropertyValue("success_to_mail"),emailTitle, emailContent);
Log.info("email send to "+ReadProperties.getPropertyValue("success_to_mail")+" success");
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
Log.fatal("email send fail :"+e.getMessage());
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getTime()
{
java.util.Calendar c=java.util.Calendar.getInstance();
java.text.SimpleDateFormat f=new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
return f.format(c.getTime());
}
}
demo.java——测试类
package com.webtest.demo;
import static org.testng.Assert.assertTrue;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.webtest.core.BaseTest;
public class demo extends BaseTest{
@Test()
public void demo() {
System.out.println("hello");
}
}
Log.java——关于日志
package com.webtest.utils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log {
static Logger logger = LogManager.getLogger(Log.class.getName());
public static void startTestCase() {
logger.info("----------------------");
}
public static void endTestCase() {
logger.info("----------------------");
}
public static void fatal(String msg) {
logger.fatal(msg);
}
public static void error(String msg) {
logger.error(msg);
}
public static void warn(String msg) {
logger.warn(msg);
}
public static void info(String msg) {
logger.info(msg);
}
public static void debug(String msg) {
logger.debug(msg);
}
}
ReadProperties.java——读取.propertiese文件中的数据
package com.webtest.utils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.testng.annotations.Test;
public class ReadProperties {
public static final String filePath="conf/config.properties";
public static String getPropertyValue(String key) throws IOException {
Properties prop = new Properties();
FileInputStream fis = new FileInputStream(filePath);
prop.load(fis);
fis.close();
return prop.getProperty(key);
}
}
config.propertises——存放参数
log_path=conf/testlog.properties
conf_root=conf/
data_root=data/
driverType=firefox
object_root=object/
base_url=http://localhost:8032/mymovie
host=localhost
port=4444
screen_name=D:\\edutest\\screenshot
gecko_driver=D:\\my_software\\selenium\\geckodriver.exe
firefox_path=D:\\my_software\\FireFox\\firefox.exe
chrome_path=D:\\demo\\chromedriver.exe
ie_path=D:\\demo\\IEDriverServer.exe
output_directory=test-output
timeout = 3000
enable_email=true
mail_title=hello
to_mail=收件人邮箱
success_to_mail=收件人邮箱
reportTemplate.html——发送的测试报告的模板
<div style="font-size:12px">自动化测试报告-----${date?string("yyyy-MM-dd HH:mm:ss")}
<br/>本次共运行自动化case:${casesize}个,其中FAIL:${failcasesize}个
<br/>
<br/>
<div>
<table width="100%" border="1" cellspacing="0" style="font-size:12px; font-family:'MS Serif', 'New York', serif;">
<!-- 失败case列表-->
<#if failedList?size gt 0>
<tr height="40">
<th colspan="4" align="left" nowrap bgcolor="#66CC33" scope="col"><div style="color:red; ">以下case执行失败:</div>
</th>
</tr>
<tr bgcolor="#FFCC66" height="35">
<th width="8%" nowrap scope="col">序号</th>
<th width="15%" scope="col">test method</th>
<th width="45%" nowrap scope="col">case title</th>
<th nowrap scope="col">测试结论</th>
</tr>
<#list failedList as case>
<tr >
<td align="center">${case_index+1}</td>
<td>${case.getMethod()}</td>
<td>${case.getAttribute("name")}</td>
<td>
<div style="color:red;">fail</div>
</td>
</tr>
</#list>
</#if>
<!--成功case列表-->
<#if (passedList?size gt 0)>
<tr height="40">
<th colspan="4" align="left" nowrap bgcolor="#66CC33" scope="col">以下case执行成功</th>
</tr>
<tr bgcolor="#FFCC66" height="35">
<th width="8%" nowrap scope="col">序号</th>
<th width="15%" scope="col">test method</th>
<th width="45%" nowrap scope="col">case title</th>
<th nowrap scope="col">测试结论</th>
</tr>
<#list passedList as case>
<tr >
<td align="center">${case_index+1}</td>
<td>${case.getMethod()}</td>
<td>${case.getAttribute("name")}</td>
<td>
PASS
</td>
</tr>
</#list>
</#if>
</table>
</div>
freemarker.xml——执行监听器和测试类
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="s1" verbose="1" >
<listeners>
<listener class-name="com.freemarker.WebTestListener" />
</listeners>
<test name="test1">
<classes>
<class name="com.webtest.demo.demo" />
</classes>
</test>
</suite>
邮件结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20181126191320437.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzIzNDQ1MQ==,size_16,color_FFFFFF,t_70)