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测试用法的更多相关文章

  1. JUnit测试工具在项目中的用法

    0:33 2013/6/26 三大框架整合时为什么要对项目进行junit测试: |__目的是测试配置文件对不对,能跑通就可以进行开发了 具体测试步骤: |__1.对hibernate进行测试 配置hi ...

  2. 关于intellij IDEA 上junit的用法

    话说,最近正在看视频学java.里面有个叫做junit的东西很有用.但是实话说我摆弄了半天都没弄明白. 今天呢通过一些资料,终于弄清楚了junit的大致用法,这里写出来,用以分享和备忘. 首先,环境和 ...

  3. 使用Cobertura统计JUnit测试覆盖率

    这是一个JavaProject,关于Cobertura的用法详见代码注释 首先是应用代码(即被测试的代码) package com.jadyer.service; public class Calcu ...

  4. 原创:Spring整合junit测试框架(简易教程 基于myeclipse,不需要麻烦的导包)

    我用的是myeclipse 10,之前一直想要用junit来测试含有spring注解或动态注入的类方法,可是由于在网上找的相关的jar文件进行测试,老是报这样那样的错误,今天无意中发现myeclips ...

  5. Java Junit测试框架

    Java    Junit测试框架 1.相关概念 Ø JUnit:是一个开发源代码的Java测试框架,用于编写和运行可重复的测试.它是用于单元测试框架体系xUnit的一个实例(用于java语言).主要 ...

  6. 002杰信-陌生的maven-web项目整改成我们熟悉的Web架构;classpath的含义;ssm框架的整合;junit测试

    这篇博客的资源来源于创智播客,先在此申明.这篇博客的出发点是jk项目,传智的做法是Maven的web模板生成的,但是这样子的结构目录与我们熟知的Web项目的结构目录相差很大,所以要按照我们熟知的项目结 ...

  7. 使用Junit测试框架学习Java

    前言 在日常的开发中,离不开单元测试,而且在学习Java时,特别是在测试不同API使用时要不停的写main方法,显得很繁琐,所以这里介绍使用Junit学习Java的方法.此外,我使用log4j将结果输 ...

  8. 复利计算器(软件工程)及Junit测试———郭志豪

    计算:1.本金为100万,利率或者投资回报率为3%,投资年限为30年,那么,30年后所获得的利息收入:按复利计算公式来计算就是:1,000,000×(1+3%)^30 客户提出: 2.如果按照单利计算 ...

  9. Junit测试框架 Tips

    关于Junit测试框架使用的几点总结: 1.Junit中的测试注解: @Test →每个测试方法前都需要添加该注解,这样才能使你的测试方法交给Junit去执行. @Before →在每个测试方法执行前 ...

随机推荐

  1. 开关调色新世界BP2888电源解决方案

    LED智能方案经过几年的拼杀,已经风靡照明界.但人们渐渐发现,对照明来说,一味追求花哨的功能并不被市场所认同,而其中开关调色,以其简单易操作的特点,已逐步融入广大消费者的生活习惯中.对吸顶灯,面板灯等 ...

  2. 可视化Git版本管理工具SourceTree的使用

    最近去了新公司,发现公司使用的团队版本管理工具是SourceTree,本人一直是SVN的热衷粉,很少使用git,所以从头学习git及可视化客户端SourceTree的使用,本贴只针对新手,大牛可以无视 ...

  3. ReactNative学习之Html基础

    前言: React Native开发作为一种新型的移动开发方式,个人觉得App的一部分需求会逐步替换成这种方式,也是公司移动开发人员所必须掌握的一种开发技术,所以鉴于这种情况我觉得很有必要学习一下,特 ...

  4. 《物联网框架ServerSuperIO教程》-20.网络通讯控制器分组,提高交互的负载平衡能力。v3.6.6 版本发布

    20.1     概述 ServerSuperIO原来在网络通讯模式下,只有一个网络控制器,在自控模式.并发模式和单例模式下时都是异步处理返回的数据,并不会出现性能问题.但是在轮询模式下,一个网络控制 ...

  5. jsonp跨域再谈

    昨天面试雷锋网,问到了jsonp跨域的问题,其实这个问题之前就会的,没有多大的深入,记得有一个名词在跨域中出现,就是同源机制, JavaScript是一种在Web开发中经常使用的前端动态脚本技术.在J ...

  6. java音视频编解码问题:16/24/32位位音频byte[]转换为小端序short[],int[],以byte[]转short[]为例

    前言:Java默认采用大端序存储方式,实际编码的音频数据是小端序,如果处理单8bit的音频当然不需要做转换,但是如果是16bit或者以上的就需要处理成小端序字节顺序. 注:大.小端序指的是字节的存储顺 ...

  7. [BZOJ1415]聪聪和可可

    Input 数据的第1行为两个整数N和E,以空格分隔,分别表示森林中的景点数和连接相邻景点的路的条数. 第2行包含两个整数C和M,以空格分隔,分别表示初始时聪聪和可可所在的景点的编号. 接下来E行,每 ...

  8. java入门学习笔记之2(Java中的字符串操作)

    因为对Python很熟悉,看着Java的各种字符串操作就不自觉的代入Python的实现方法上,于是就将Java实现方式与Python实现方式都写下来了. 先说一下总结,Java的字符串类String本 ...

  9. Linux(UBUNTU) 下安装Eclipse

    到目前为止,Eclipse 的官方最新版本为 Eclipse Kepler (4.3.2),我们可以使用如下步骤在 Ubuntu 14.04 或其它 Ubuntu 版本中进行快速安装. 1.安装Ope ...

  10. R 包 安装 卸载 查看版本

    R 查看包的版本 version> packageVersion("snow") 卸载包remove.packages 从源码安装包install.packages(path ...