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.pswp.cn/news/371747.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/371747.shtml
英文地址,請注明出處:http://en.pswp.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…