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. 一个Monad的不严谨介绍

    一个单子(Monad)说白了不过就是自函子范畴上的一个幺半群而已,这有什么难以理解的?* 之前了解了下Monad,后来一段时间没碰,最近研究Parser用到Monad时发现又不懂了.现在重新折腾,趁着 ...

  2. Submin1安装记录(CentOS5)

    安装SVN和Apache wget http://opensource.wandisco.com/RPM-GPG-KEY-WANdisco -O /tmp/RPM-GPG-KEY-WANdisco & ...

  3. stickUp.js:98 Uncaught ReferenceError: vartop is not defined at HTMLDocument.<anonymous> (stickUp.js:98)

    附加var vartop = 0;在var topMargin = 0;这之后,这里是我附加的代码:$(document).ready(function(){ var contentButton = ...

  4. [HDU1001] Sum Problem

    Problem Description Hey, welcome to HDOJ(Hangzhou Dianzi University Online Judge). In this problem, ...

  5. java基础(九章)

    一.理解查询的机制 客户端应用程序(c/s.b/s)向后台服务器的DB发送一条select语句进行查询操作,会将结果集(虚拟表)返回到客户端应用程序 二.select语句 1.查询表中的全部列和行 s ...

  6. 【锋利的jQuery】中全局事件ajaxStart、ajaxStop不执行

    最近一直都在研究[锋利的jQuery],确实是一本好书,受益匪浅.但由于技术发展及版本更新等原因,里面还是有些坑需要踩的. 比如:第六章七节中提到的全局事件ajaxStart.ajaxStop照着案例 ...

  7. iOS开发之资讯类App常用分类控件的封装与实现(CollectionView+Swift3.0+)

    今天博客中,我们就来实现一下一些常用资讯类App中常用的分类选择的控件的封装.本篇博客中没有使用到什么新的技术点,如果非得说用到了什么新的技术点的话,那么勉强的说,用到了一些iOS9以后UIColle ...

  8. 记一次 net 使用 data.oracleclient 使用错误

    前提: 公司除了领导和开发人员具有管理员权限,其他人员使用的都是域账号. 过程: 应要求开发一个 winfrom项目,使用data.oracleclient  本地开发,调试无误,放到服务器共享域用户 ...

  9. JDBC加载数据库驱动的方式

    JDBC作为数据库访问的规范接口,其中只是定义一些接口.具体的实现是由各个数据库厂商来完成. 一.重要的接口: 1.public interface Driver 每个驱动程序类必须实现的接口.Jav ...

  10. 配置php支持gd函数模块

    配置php支持gd函数模块 今天在联系上线源码包tttuangou 的时候,出现了对gd_info和imagecreatefromjpeg模块缺失的提示,我丈二和尚摸不着头脑,决定彻底学习一番 什么是 ...