Tomcat上下文JUnit @Rule

创建测试上下文的JUnit @Rule的初稿。 这可以用Spring上下文规则可用于 这个帖子 创建集成测试一个完整的Spring上下文。
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.log4j.Logger;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.lang.reflect.Method;
import java.sql.Driver;
import java.sql.DriverManager;/*** Creates an context for tests using an Apache Tomcat server.xml.** https://blogs.oracle.com/randystuph/entry/injecting_jndi_datasources_for_junit** @author alex.collins*/
public class TomcatContextRule implements TestRule {public static final Logger LOGGER = Logger.getLogger(CatalinaContextRule.class);/*** Creates all the sub-contexts for a name.*/public static void createSubContexts(Context ctx, String name) {String subContext = '';for (String x : name.substring(0, name.lastIndexOf('/')).split('/')) {subContext += x;try {ctx.createSubcontext(subContext);} catch (NamingException e) {// nop}subContext += '/';}}private final File serverXml;public TomcatContextRule(File serverXml, Object target) {if (serverXml == null || !serverXml.isFile()) {throw new IllegalArgumentException();}if (target == null) {throw new IllegalArgumentException();}this.serverXml = serverXml;}public Statement apply(final Statement statement, Description description) {return new Statement() {@Overridepublic void evaluate() throws Throwable {createInitialContext();try {statement.evaluate();} finally {destroyInitialContext();}}};}private void createInitialContext() throws Exception {LOGGER.info('creating context');System.setProperty(Context.INITIAL_CONTEXT_FACTORY, org.apache.naming.java.javaURLContextFactory.class.getName());System.setProperty(Context.URL_PKG_PREFIXES, 'org.apache.naming');final InitialContext ic = new InitialContext();createSubContexts(ic, 'java:/comp/env');final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();final DocumentBuilder builder = factory.newDocumentBuilder();final Document document = builder.parse(serverXml);// create Environment{final NodeList envs = document.getElementsByTagName('Environment');for (int i = 0; i < envs.getLength(); i++) {final Element env = (Element)envs.item(i); // must be Elementfinal String name = 'java:comp/env/' + env.getAttribute('name');final Object instance = Class.forName(env.getAttribute('type')).getConstructor(String.class).newInstance(env.getAttribute('value'));LOGGER.info('binding ' + name + ' <' + instance + '>');createSubContexts(ic, name);ic.bind(name, instance);}}// Resource{final NodeList resources = document.getElementsByTagName('Resource');for (int i = 0; i < resources.getLength(); i++) {final Element resource = (Element)resources.item(i); // must be Elementfinal String name = 'java:comp/env/' + resource.getAttribute('name');final Class<?> type = Class.forName(resource.getAttribute('type'));final Object instance;if (type.equals(DataSource.class)) {{@SuppressWarnings('unchecked') // this mus be driver?final Class<? extends Driver> driverClass = (Class<? extends Driver>) Class.forName(resource.getAttribute('driverClassName'));DriverManager.registerDriver(driverClass.newInstance());}final BasicDataSource dataSource = new BasicDataSource();// find all the bean attributes and set them use some reflectionfor (Method method : dataSource.getClass().getMethods()) {if (!method.getName().matches('^set.*')) {continue;}final String x = method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4);if (!resource.hasAttribute(x)) {continue;}Class<?> y = method.getParameterTypes()[0]; // might be primitiveif (y.isPrimitive()) {if (y.getName().equals('boolean')) y = Boolean.class;if (y.getName().equals('byte')) y = Byte.class;if (y.getName().equals('char')) y = Character.class;if (y.getName().equals('double')) y = Double.class;if (y.getName().equals('float')) y = Float.class;if (y.getName().equals('int')) y = Integer.class;if (y.getName().equals('long')) y = Long.class;if (y.getName().equals('short')) y = Short.class;if (y.getName().equals('void')) y = Void.class;}method.invoke(dataSource, y.getConstructor(String.class).newInstance(resource.getAttribute(x)));}instance = dataSource;} else {// not supported, yet...throw new AssertionError('type ' + type + ' not supported');}LOGGER.info('binding ' + name + ' <' + instance + '>');createSubContexts(ic, name);ic.bind(name, instance);}}}private void destroyInitialContext() {System.clearProperty(Context.INITIAL_CONTEXT_FACTORY);System.clearProperty(Context.URL_PKG_PREFIXES);LOGGER.info('context destroyed');}}

例如:

@Rulepublic TestRule rules = RuleChain.outerRule(new CatalinaContextRule(new File(getClass().getResource('/server.xml').getFile()), this)).around(new ContextRule(new String[] {'/applicationContext.xml'}, this));

这段代码在Github上 。

参考:来自我们的JCG合作伙伴 Alex Collins的Tomcat Context JUnit @Rule ,位于Alex Collins的博客博客中。


翻译自: https://www.javacodegeeks.com/2012/07/tomcat-context-junit-rule.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/371747.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

排序算法之(7)——堆排序

【堆排序的思路】 堆排序主要是利用了堆的性质。对于大顶堆&#xff1a;堆中的每一个节点的值都不小于它的孩子节点的值&#xff0c;具体可參考我的还有一篇博客http://blog.csdn.net/adminabcd/article/details/46880591&#xff0c;那么大顶堆的堆顶元素就是当前堆中全部元素…

HTML基础:基本标签简介(3)

html中有很多标签&#xff0c;下面介绍最基本的几个标签。 1、meta 是head标签中的一个辅助性标签。 有2个重要属性&#xff1a; &#xff08;1&#xff09;name 可以优化页面被搜索到的可能性。name中可以指定属性&#xff0c;content是属性值。 <html><head><…

java 字符码_Java字符编码

编码原理介绍(中文编码杂谈)&#xff1a;int -> byte可以直接使用强制类型转换: byte b (byte) aInt;这个操作是直接截取int中最低一个字节&#xff0c;如果int大于255&#xff0c;则值就会变得面目全非了byte -> int这里有两种情况&#xff0c;一种是要求保持值不变&am…

重新登录:重新登录

嗨&#xff0c;我再次回到日志中来&#xff0c;这是任何应用程序设计和开发的固有部分。 我是坚强的基础知识的忠实拥护者&#xff0c;在我的拙见中&#xff0c;日志记录是任何企业级应用程序中经常被忽略但基本的关键要素之一。 我已经写在此之前这里 。 为了理解当前文章&…

eclipse 下使用git clone

方法一&#xff1a;eclipse安装好git插件后&#xff0c;直接import-git-project from git- clone url-输入github的网址等就可以了方法二&#xff1a;使用git软件&#xff0c;到指定的目录&#xff0c;右击git bash here&#xff0c;git clone 加带有网址的文件.git,如&#xf…

linux -unrar解压缩

解压缩命令unrar的使用&#xff1a; $unrar --help用法: unrar <command>-<switch 1> -<switchN> <archive><files...><listfiles...><path_to_extract\><命令>e 解压文件到当前目录l[t,b] 列出压缩文档信…

终极JPA查询和技巧列表–第3部分

在阅读第三部分之前&#xff0c;请记住本系列的第一部分和第二部分 JPA&#xff1a;通过查询创建对象 JPA允许我们在查询内创建对象&#xff0c;并带有所需的值&#xff1a; package com.model;public class PersonDogAmountReport {private int dogAmount;private Person pe…

分治1--二分查找

分治1--二分查找 一、心得 二、题目和分析 三、代码和结果 1 #include <iostream>2 using namespace std;3 int a[10]{1,2,4,5,7,8,9,10,13,20};4 5 6 //非递归 7 int find(int i){8 int l0,r9;9 int mid(lr)/2; 10 while(l<r){ 11 mid(lr)/2; 12…

隐式意图启动一个Activity

隐式意图是通过指定一组动作或者属性实现&#xff0c;主要用于跨应用使用。 1.创建一个意图对象 Intent intent new Intent();2.设置意图过滤器 intent.setAction("android.intent.action.testActivity"); //对应于action intent.addCategory("android.intent.…

Spring自定义命名空间

Spring自定义命名空间提供了一种很好的方式来简化用于描述Spring应用程序上下文的bean定义的xml文件。 这是一个相当古老的概念&#xff0c;最初是在Spring 2.0中引入的&#xff0c;但值得不时地进行审查。 考虑一种情况&#xff0c;必须为没有自定义名称空间的Spring MVC应用程…

java二叉树代码_JAVA语言实现二叉树生成的代码教程

本文主要向大家介绍了JAVA语言实现二叉树生成的代码教程&#xff0c;通过具体的内容向大家展示&#xff0c;希望对大家学习JAVA语言有所帮助。给定某二叉树三序遍历中的两个&#xff0c;我们即可以通过生成该二叉树&#xff0c;并遍历的方法&#xff0c;求出剩下的一序&#xf…

一个回到顶部的锚点

一般网站的右下角都会有一个回到顶部的锚点&#xff0c;但是在没有学bootstrap的时候&#xff0c;我还是会想着用定位来做这个东西&#xff0c;但是现在用bootstrap来做的&#xff0c;所以将它记录下来。 <!DOCTYPE html><html> <head><title>附加导航…

jquery jgrid filterToolBar beforeSearch 修改postData

beforeSearch: function() { var posted_data $("#mygrid").jqGrid(getGridParam,postData); posted_data ["testp"]"helloTest"; }转载于:https://www.cnblogs.com/qiumingcheng/p/7141671.html

预告片:裸指关节SOA

我正在研究这个想法&#xff0c;但我不知道它是否对你们有吸引力。 我想就您是否需要进一步探讨提出您的意见。 达成协议&#xff1a;我遇到过一些团队&#xff0c;他们在使用SOA技术时由于其工具的复杂性而陷入泥潭。 我只在Java中看到过这种情况&#xff0c;但是我从一些C&am…

网页转图片 java_java-网页转图片

对比了网上常用的好几种网页转图片的开源插件&#xff0c;最后效果还不如使用原生的java直接写来得好&#xff0c;上代码&#xff0c;很简单&#xff0c;中间需要考虑网页加载延迟的问题&#xff0c;所以需要加上thread.sleep&#xff0c;休眠一下等待网页加载完成了&#xff0…

开一个新坑吧

每天读读日志 给自己动力 开个新坑&#xff08;外星殖民&#xff09; 无聊时写一写 转载于:https://www.cnblogs.com/dandansang/p/7143489.html

JMX和Spring –第1部分

这是三篇文章的第一篇&#xff0c;这三篇文章将展示如何通过JMX支持为Spring应用程序赋能。 Maven配置 这是用于设置此示例代码的Maven pom.xml&#xff1a; <project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3.org/2001/XMLSche…

maven exclude java_java – Maven:从shade插件中排除依赖项

我在mvn clean install之后看过下一个字符串Including com.sun.jersey.contribs:jersey-multipart:jar:1.5 in theshaded jar问题&#xff1a;即使我已经为maven-shade-plugin添加了exlusion,我也无法使它没有阴影(参见下面的代码)我的maven-shade-plugin&#xff1a;org.apach…

JMX和Spring –第3部分

本文是本系列的最后一篇。 看一下第1 部分和第2部分 。 在本系列的最后一篇文章中&#xff0c;我将展示如何在JDK中使用本机JMX支持来实现一种通知机制&#xff0c;该机制可以在HEAP内存超过特定阈值时向侦听器发出警报。 正如我在上一篇文章中讨论的那样&#xff0c;这种方法…

QScrollArea不能显示滚动条

转载请注明出处&#xff1a;http://www.cnblogs.com/dachen408/p/7147141.html 问题&#xff1a;QScrollArea不能显示滚动条 解决方案&#xff1a;设置QScrollArea->setWidgetResizeable&#xff08;false&#xff09;解决问题。 例子&#xff1a; ui.scrollArea->setWi…