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. springboot 中使用websocket简单例子

    gradle 中添加依赖,引入websocket支持 compile("org.springframework.boot:spring-boot-starter-websocket:${sp ...

  2. Github 开源:使用控制器操作 WinForm/WPF 控件( Sheng.Winform.Controls.Controller)

    利用午休时间继续把过去写的一些代码翻出来说一说,文章可能写的比较简略,但是我会努力把核心意思表达清楚,具体代码可直接访问 Github 获取. Github 地址:https://github.com ...

  3. Windows 7 下安装mysql-5.7.18-winx64.zip

    mysql-5.7以后压缩包安装有了不小的变化 第一步:到官网下载https://dev.mysql.com/downloads/mysql/ 第二步:解压到一个文件夹 第三步:配置环境变量 把;%M ...

  4. 微信小程序开发 -- 02

    微信小程序开发 --02 微信小程序在开发中,难度系数不是很大,其中应用的技术也是web开发中常用的技术,虽然在微信开发者工具中的叫法与常见的web开发的叫法不太一样. 首先,在微信小程序开发中,代码 ...

  5. shell网络客户端

    需要把线上的access日志发送到另一个程序接收 开始想着用python实现,虽然python也有实现类似tail -F的方式,但太麻烦,而且效率也有折扣 偶然发现了shell可以实现网络client ...

  6. Javascript数组操作详细解答

    数组push()方法向数组尾部追加新元素,返回值为新数组的长度;括号里面带新追加的元素pop()方法从数组尾部移除一个元素,返回值为移除的元素括号里面不能带参数 shift()方法从数组头部移除一个元 ...

  7. js删除 object中的空值

    var data = { a: 'a', b: '' } 删除 b和''的配对, /** * Delete all null (or undefined) properties from an obj ...

  8. ionic复选框应用

    如图:在项目中我需要实现这个效果布局和功能(进入页面默认全选,点击之后可以不选择) HTML代码: <div class="row" ng-repeat="engi ...

  9. A. Karen and Morning

    A. Karen and Morning time limit per test 2 seconds  memory limit per test 512 megabytes input standa ...

  10. 【转载】Sublime Text 3065 Keygen and Patcher

    原始日期:2014-10-01 18:25      差不多时隔一年了,Sublime Text 终于更新啦!相信很多友友都已经升级到3065版本了,所以我也特地抽空为大家做了个新版补丁.该补丁仅作为 ...