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 →在每个测试方法执行前 ...
随机推荐
- 关于bootstrap中cropper的截图上传问题
之前做一个关于截图的东东,搞了好久终于弄好了,其主要关键是把前端截图的数据(x坐标,y坐标,宽度,高度和旋转角度)传到后台,然后在后台对图片做相关处理,记录一下方便以后查看. 后台配置为ssm. Ja ...
- 设计模式二:MVC
先附上部分代码: /* *MVC 模式代表 Model-View-Controller(模型-视图-控制器) 模式.这种模式用于应用程序的分层开发. *Model(模型) - 模型代表一个存取数据的对 ...
- 在linux下利用信号量实现一个写者线程多个读者线程
#include<pthread.h> #include<string.h> #include<stdlib.h> #include<stdio.h> ...
- 创建对象的N种模式
1 new Object() 先创建一个Object实例,然后为它添加属性和方法 var Person = new Object() Person.name = 'hl' Person.sayName ...
- 再来写一个随机数解决方案,对Random再来一次封装
本文提供对Random的封装,简化并扩展了其功能 获取随机数,确保同时调用不会重复 //new Random().Next(5); RandomTask.Next(); 从一个列表中,随机获取其中某个 ...
- [0] 解决版本冲突-使用SVN主干与分支功能
解决版本冲突-使用SVN主干与分支功能 1 前言 大多数产品开发存在这样一个生命周期:编码.测试.发布,然后不断重复.通常是这样的开发步骤: 1) 开发人员开发完毕某一版本(如版本A)功能后, ...
- 静态库 .a 转成共享库 .so
.a 是有一系列 .o 文件通过 ar 程序打包在一起的静态库,要把它转成动态库只需先解开,生成一堆 .o 文件,再通过编译器(比如 gcc 或 ifort,视具体情况而定)编成动态库即可. ar - ...
- 由SpringMVC中RequetContextListener说起
零.引言 RequetContextListener从名字结尾Listener来看就知道属于监听器. 所谓监听器就是监听某种动作,在其开始(初始化)和结束(销毁)的时候进行某些操作. 由此可以猜测:该 ...
- 解决安卓手机input获取焦点时会将底部固定定位按钮顶起的问题
一个页面上有个固定在底部的按钮,页面中有个input框,点击input框获取焦点时,在苹果手机上没事,但在安卓手机上弹出的键盘会将按钮顶起来,这就很不好看了,想了个办法解决一下.之前一直觉得用inpu ...
- AVAudioSession(2):定义一个 Audio Session
本文转自:AVAudioSession(2):定义一个 Audio Session | www.samirchen.com 本文内容主要来源于 Defining an Audio Session. A ...