Wiser的Junit测试用法
package org.jbpm.process.workitem.email; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import javax.mail.AuthenticationFailedException;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.drools.core.process.instance.impl.DefaultWorkItemManager;
import org.drools.core.process.instance.impl.WorkItemImpl;
import org.jbpm.test.util.AbstractBaseTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.kie.api.runtime.process.WorkItemManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.subethamail.smtp.AuthenticationHandler;
import org.subethamail.smtp.AuthenticationHandlerFactory;
import org.subethamail.smtp.auth.LoginAuthenticationHandlerFactory;
import org.subethamail.smtp.auth.LoginFailedException;
import org.subethamail.smtp.auth.MultipleAuthenticationHandlerFactory;
import org.subethamail.smtp.auth.PlainAuthenticationHandlerFactory;
import org.subethamail.smtp.auth.UsernamePasswordValidator;
import org.subethamail.wiser.Wiser;
import org.subethamail.wiser.WiserMessage; public class SendHtmlTest extends AbstractBaseTest {
private static final Logger logger = LoggerFactory
.getLogger(SendHtmlTest.class);
private Wiser wiser;
private String emailHost;
private String emailPort;
private static String authUsername = "cpark";
private static String authPassword = "yourbehindwhat?";
private Random random = new Random();
private int uniqueTestNum = -1; @Before
public void setUp() throws Exception {
uniqueTestNum = random.nextInt(Integer.MAX_VALUE);
emailHost = "localhost";
int emailPortInt;
do {
emailPortInt = random.nextInt((2 * Short.MAX_VALUE - 1));
} while (emailPortInt < 4096);
emailPort = Integer.toString(emailPortInt);
wiser = new Wiser(Integer.parseInt(emailPort));
wiser.start();
} @After
public void tearDown() throws Exception {
if (wiser != null) {
wiser.getMessages().clear();
wiser.stop();
wiser = null;
}
} @SuppressWarnings("unused")
private class ExtendedConnection extends Connection {
private String extraField;
} @Test
public void testConnectionEquals() {
Connection connA = new Connection();
Connection connB = new Connection();
// null test
assertTrue(!connA.equals(null));
// different class test
assertTrue(!connA.equals("og"));
// extended class test
ExtendedConnection connExt = new ExtendedConnection();
assertTrue(!connA.equals(connExt));
// null fields test
assertTrue(connA.equals(connB));
// all null vs filled field test
connA.setHost("Human");
connA.setPort("Skin");
connA.setUserName("Viral");
connA.setPassword("Protein Gate");
assertTrue(!connA.equals(connB));
// filled field test
connB.setHost(connA.getHost());
connB.setPort(new String(connA.getPort()));
connB.setUserName(connA.getUserName());
connB.setPassword(connA.getPassword());
assertTrue(connA.equals(connB));
// some null vs filled field test
connA.setPassword(null);
connB.setPassword(null);
assertTrue(connA.equals(connB));
// boolean
connA.setStartTls(true);
assertTrue(!connA.equals(connB));
connB.setStartTls(true);
assertTrue(connA.equals(connB));
connB.setStartTls(false);
assertTrue(!connA.equals(connB));
} @Test
public void verifyWiserServerWorks() throws Exception {
// Input
String testMethodName = Thread.currentThread().getStackTrace()[1]
.getMethodName();
String toAddress = "boyd@crowdergang.org";
String fromAddress = "rgivens@kty.us.gov";
// Setup email
WorkItemImpl workItem = createEmailWorkItem(toAddress, fromAddress,
testMethodName);
Connection connection = new Connection(emailHost, emailPort);
sendAndCheckThatMessagesAreSent(workItem, connection);
} @Test
public void sendHtmlWithAuthentication() throws Exception {
// Add authentication to Wiser SMTP server
wiser.getServer().setAuthenticationHandlerFactory(
new TestAuthHandlerFactory());
// Input
String testMethodName = Thread.currentThread().getStackTrace()[1]
.getMethodName();
String toAddress = "rgivens@kty.us.gov";
String fromAddress = "whawkins@kty.us.gov";
// Setup email
WorkItemImpl workItem = createEmailWorkItem(toAddress, fromAddress,
testMethodName);
Connection connection = new Connection(emailHost, emailPort,
authUsername, authPassword);
sendAndCheckThatMessagesAreSent(workItem, connection);
} @Test
public void sendHtmlWithAuthenticationAndAttachments() throws Exception {
// Add authentication to Wiser SMTP server
wiser.getServer().setAuthenticationHandlerFactory(
new TestAuthHandlerFactory());
// Input
String testMethodName = Thread.currentThread().getStackTrace()[1]
.getMethodName();
String toAddress = "rgivens@kty.us.gov";
String fromAddress = "whawkins@kty.us.gov";
// Setup email
WorkItemImpl workItem = createEmailWorkItemWithAttachment(toAddress,
fromAddress, testMethodName);
Connection connection = new Connection(emailHost, emailPort,
authUsername, authPassword);
// send email
Email email = EmailWorkItemHandler.createEmail(workItem, connection);
SendHtml.sendHtml(email, connection);
List<WiserMessage> messages = wiser.getMessages();
assertEquals(1, messages.size());
MimeMessage message = messages.get(0).getMimeMessage();
assertEquals(workItem.getParameter("Subject"), message.getSubject());
assertTrue(Arrays.equals(
InternetAddress.parse((String) workItem.getParameter("To")),
message.getRecipients(RecipientType.TO)));
assertTrue(message.getContent() instanceof Multipart);
Multipart multipart = (Multipart) message.getContent();
assertEquals(2, multipart.getCount());
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
continue;
// dealing with attachments only
}
assertEquals("email.gif", bodyPart.getFileName());
}
} @Test
public void sendHtmlWithBadAuthentication() throws Exception {
// Add authentication to Wiser SMTP server
wiser.getServer().setAuthenticationHandlerFactory(
new TestAuthHandlerFactory());
// Input
String testMethodName = Thread.currentThread().getStackTrace()[1]
.getMethodName();
String toAddress = "mags@bennetstore.com";
String fromAddress = "rgivens@kty.us.gov";
checkBadAuthentication(toAddress, fromAddress, testMethodName,
authUsername, "bad password");
checkBadAuthentication(toAddress, fromAddress, testMethodName,
"badUserName", authPassword);
} @Test
public void useEmailWorkItemHandlerWithAuthentication() throws Exception {
// Add authentication to Wiser SMTP server
wiser.getServer().setAuthenticationHandlerFactory(
new TestAuthHandlerFactory());
// Input
String testMethodName = Thread.currentThread().getStackTrace()[1]
.getMethodName();
String toAddress = "rgivens@yahoo.com";
String fromAddress = "rgivens@kty.us.gov";
EmailWorkItemHandler handler = new EmailWorkItemHandler();
handler.setConnection(emailHost, emailPort, authUsername, authPassword);
WorkItemImpl workItem = new WorkItemImpl();
workItem.setParameter("To", toAddress);
workItem.setParameter("From", fromAddress);
workItem.setParameter("Reply-To", fromAddress);
workItem.setParameter("Subject", "Test mail for " + testMethodName);
workItem.setParameter("Body",
"Don't forget to check on Boyd later today.");
WorkItemManager manager = new DefaultWorkItemManager(null);
handler.executeWorkItem(workItem, manager);
List<WiserMessage> messages = wiser.getMessages();
assertEquals(1, messages.size());
for (WiserMessage wiserMessage : messages) {
MimeMessage message = wiserMessage.getMimeMessage();
assertEquals(workItem.getParameter("Subject"), message.getSubject());
assertTrue(Arrays.equals(InternetAddress.parse(toAddress),
message.getRecipients(RecipientType.TO)));
}
} /** * Helper methods */
private void sendAndCheckThatMessagesAreSent(WorkItemImpl workItem,
Connection connection) throws Exception {
// send email
Email email = EmailWorkItemHandler.createEmail(workItem, connection);
SendHtml.sendHtml(email, connection);
List<WiserMessage> messages = wiser.getMessages();
assertEquals(1, messages.size());
for (WiserMessage wiserMessage : messages) {
MimeMessage message = wiserMessage.getMimeMessage();
assertEquals(workItem.getParameter("Subject"), message.getSubject());
assertTrue(Arrays
.equals(InternetAddress.parse((String) workItem
.getParameter("To")), message
.getRecipients(RecipientType.TO)));
}
} private void checkBadAuthentication(String toAddress, String fromAddress,
String testMethodName, String username, String password) {
// Setup email
WorkItemImpl workItem = createEmailWorkItem(toAddress, fromAddress,
testMethodName);
Connection connection = new Connection(emailHost, emailPort, username,
password);
// send email
Email email = EmailWorkItemHandler.createEmail(workItem, connection);
try {
SendHtml.sendHtml(email, connection);
} catch (Throwable t) {
assertTrue("Unexpected exception of type "
+ t.getClass().getSimpleName() + ", not "
+ t.getClass().getSimpleName(),
(t instanceof RuntimeException));
assertNotNull("Expected RuntimeException to have a cause.",
t.getCause());
Throwable cause = t.getCause();
assertNotNull("Expected cause to have a cause.", cause.getCause());
cause = cause.getCause();
assertTrue("Unexpected exception of type "
+ cause.getClass().getSimpleName() + ", not "
+ cause.getClass().getSimpleName(),
(cause instanceof AuthenticationFailedException));
}
} private WorkItemImpl createEmailWorkItem(String toAddress,
String fromAddress, String testMethodName) {
WorkItemImpl workItem = new WorkItemImpl();
workItem.setParameter("To", toAddress);
workItem.setParameter("From", fromAddress);
workItem.setParameter("Reply-To", fromAddress);
String subject = this.getClass().getSimpleName() + " test message ["
+ uniqueTestNum + "]";
String body = "\nThis is the test message generated by the "
+ testMethodName + " test (" + uniqueTestNum + ").\n";
workItem.setParameter("Subject", subject);
workItem.setParameter("Body", body);
return workItem;
} private WorkItemImpl createEmailWorkItemWithAttachment(String toAddress,
String fromAddress, String testMethodName) {
WorkItemImpl workItem = new WorkItemImpl();
workItem.setParameter("To", toAddress);
workItem.setParameter("From", fromAddress);
workItem.setParameter("Reply-To", fromAddress);
String subject = this.getClass().getSimpleName() + " test message ["
+ uniqueTestNum + "]";
String body = "\nThis is the test message generated by the "
+ testMethodName + " test (" + uniqueTestNum + ").\n";
workItem.setParameter("Subject", subject);
workItem.setParameter("Body", body);
workItem.setParameter("Attachments", "classpath:/icons/email.gif");
return workItem;
} private static class TestAuthHandlerFactory implements
AuthenticationHandlerFactory {
MultipleAuthenticationHandlerFactory authHandleFactory = new MultipleAuthenticationHandlerFactory(); public TestAuthHandlerFactory() {
UsernamePasswordValidator validator = new UsernamePasswordValidator() {
public void login(String username, String password)
throws LoginFailedException {
if (!authUsername.equals(username)
|| !authPassword.equals(password)) {
logger.debug(
"Tried to login with user/password [{}/{}]",
username, password);
throw new LoginFailedException(
"Incorrect password for user " + authUsername);
}
}
};
authHandleFactory.addFactory(new LoginAuthenticationHandlerFactory(
validator));
authHandleFactory.addFactory(new PlainAuthenticationHandlerFactory(
validator));
} public AuthenticationHandler create() {
return authHandleFactory.create();
} public List<String> getAuthenticationMechanisms() {
return authHandleFactory.getAuthenticationMechanisms();
}
}
}
关于javamail的Junit测试,找了很久才找到如何测试验证SMTP服务器。
Wiser的Junit测试用法的更多相关文章
- JUnit测试工具在项目中的用法
0:33 2013/6/26 三大框架整合时为什么要对项目进行junit测试: |__目的是测试配置文件对不对,能跑通就可以进行开发了 具体测试步骤: |__1.对hibernate进行测试 配置hi ...
- 关于intellij IDEA 上junit的用法
话说,最近正在看视频学java.里面有个叫做junit的东西很有用.但是实话说我摆弄了半天都没弄明白. 今天呢通过一些资料,终于弄清楚了junit的大致用法,这里写出来,用以分享和备忘. 首先,环境和 ...
- 使用Cobertura统计JUnit测试覆盖率
这是一个JavaProject,关于Cobertura的用法详见代码注释 首先是应用代码(即被测试的代码) package com.jadyer.service; public class Calcu ...
- 原创:Spring整合junit测试框架(简易教程 基于myeclipse,不需要麻烦的导包)
我用的是myeclipse 10,之前一直想要用junit来测试含有spring注解或动态注入的类方法,可是由于在网上找的相关的jar文件进行测试,老是报这样那样的错误,今天无意中发现myeclips ...
- Java Junit测试框架
Java Junit测试框架 1.相关概念 Ø JUnit:是一个开发源代码的Java测试框架,用于编写和运行可重复的测试.它是用于单元测试框架体系xUnit的一个实例(用于java语言).主要 ...
- 002杰信-陌生的maven-web项目整改成我们熟悉的Web架构;classpath的含义;ssm框架的整合;junit测试
这篇博客的资源来源于创智播客,先在此申明.这篇博客的出发点是jk项目,传智的做法是Maven的web模板生成的,但是这样子的结构目录与我们熟知的Web项目的结构目录相差很大,所以要按照我们熟知的项目结 ...
- 使用Junit测试框架学习Java
前言 在日常的开发中,离不开单元测试,而且在学习Java时,特别是在测试不同API使用时要不停的写main方法,显得很繁琐,所以这里介绍使用Junit学习Java的方法.此外,我使用log4j将结果输 ...
- 复利计算器(软件工程)及Junit测试———郭志豪
计算:1.本金为100万,利率或者投资回报率为3%,投资年限为30年,那么,30年后所获得的利息收入:按复利计算公式来计算就是:1,000,000×(1+3%)^30 客户提出: 2.如果按照单利计算 ...
- Junit测试框架 Tips
关于Junit测试框架使用的几点总结: 1.Junit中的测试注解: @Test →每个测试方法前都需要添加该注解,这样才能使你的测试方法交给Junit去执行. @Before →在每个测试方法执行前 ...
随机推荐
- bootstrap4中文版(纯手工翻译)
1初步开始 1.1依赖 这个仓储包含一系列基于bootstrap标识和css样式的原生angular2指令.所以是不需要依赖jq和bootstrap.js的.只需要以下依赖即可: Angular(需要 ...
- R绘图字体解决方案(转)
COS论坛里面经常会遇到的一个问题就是绘图时中文字体怎么解决.最初,一个流行的方法是使用family = "GB1",但一般这样做出来的图比较难看,而且并没有完全解决问题.后来发现 ...
- 《算法4》2.1 - 插入排序算法(Insertion Sort), Python实现
排序算法列表电梯: 选择排序算法:详见 Selection Sort 插入排序算法(Insertion Sort):非常适用于小数组和部分排序好的数组,是应用比较多的算法.详见本文 插入排序算法的语言 ...
- jquery+js实现鼠标位移放大镜效果
jQuery实现仿某东商品详情页放大镜效果 用jquery+js实现放大镜效果,效果大概如下图! 效果是不是大家很感兴趣,放大镜查看细节,下边大家可以详细看一看具体是怎么实现的.下边直接看代码! HT ...
- html打造动画【系列1】- 萌萌的大白
每个人心中都有一个暖暖的大白,blingbling的大眼睛~软软的肚子~宽厚的肩膀~善良的心肠~如果可以,我愿意沦陷在大白的肚子里永远不出来,哈哈~毛球要失宠咯~ 哈哈哈 每个人都是独立的个体,大白也 ...
- Javascript检测值
检测原始值用typeof javascript有五种原始类型,分别为字符串.数字.布尔值.null和undefined 判断一个值是什么类型的字符串,可以通过typeof typeof variabl ...
- Azure 基础:Blob Storage
Azure Storage 是微软 Azure 云提供的云端存储解决方案,当前支持的存储类型有 Blob.Queue.File 和 Table. 笔者在前文中介绍了 Table Storage 的基本 ...
- MACOS关闭指定端口
因为用IDEA写项目的时候,有的时候结束Jetty导致端口没有释放,所以会出现占用的情况. MacOS结束端口占用进程的命令,和Linux的一样.先执行如下命令: lsof -i:8080 会有类似下 ...
- node.js零基础详细教程(6):mongodb数据库操作
第六章 建议学习时间4小时 课程共10章 学习方式:详细阅读,并手动实现相关代码 学习目标:此教程将教会大家 安装Node.搭建服务器.express.mysql.mongodb.编写后台业务逻辑. ...
- PHP中的抽象类与抽象方法/静态属性和静态方法/PHP中的单利模式(单态模式)/串行化与反串行化(序列化与反序列化)/约束类型/魔术方法小结
前 言 OOP 学习了好久的PHP,今天来总结一下PHP中的抽象类与抽象方法/静态属性和静态方法/PHP中的单利模式(单态模式)/串行化与反串行化(序列化与反序列化). 1 PHP中的抽象 ...