Injecting JNDI datasources for JUnit Tests outside of a container

本文介绍如何在JUnit测试环境中手动配置数据源,通过创建JNDI上下文和设置数据库连接参数,实现不依赖容器的数据源注入。适用于需要进行数据库访问的单元测试场景。
I was working on some webservices that we're moving into libraries the other day, and needed to run a full set of tests using junit, but outside of a container. I didn't want to create and deploy an entire test harness, I just wanted to run the junit tests in the nb ide. But I couldn't get the test to inject the datasource resource so it was usable. I finally got it working, but I'll spare you all the pain I went through to get here. Here's how I did it in my test class:
    @BeforeClass
public static void setUpClass() throws Exception {
// rcarver - setup the jndi context and the datasource
try {
// Create initial context
System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.naming.java.javaURLContextFactory");
System.setProperty(Context.URL_PKG_PREFIXES,
"org.apache.naming");
InitialContext ic = new InitialContext();

ic.createSubcontext("java:");
ic.createSubcontext("java:/comp");
ic.createSubcontext("java:/comp/env");
ic.createSubcontext("java:/comp/env/jdbc");

// Construct DataSource
OracleConnectionPoolDataSource ds = new OracleConnectionPoolDataSource();
ds.setURL("jdbc:oracle:thin:@host:port:db");
ds.setUser("MY_USER_NAME");
ds.setPassword("MY_USER_PASSWORD");

ic.bind("java:/comp/env/jdbc/nameofmyjdbcresource", ds);
} catch (NamingException ex) {
Logger.getLogger(MyDAOTest.class.getName()).log(Level.SEVERE, null, ex);
}

}

As you can see, in this case I used the OracleConnectionPoolDataSource,
you should use the datasource for your db connection. Don't forget to
link in the appropriate db jar (in my case it was ojdbc14.jar)
The code that is used to retrieve the datasource (which works for test
and production) looks like this:

Context initContext = new InitialContext();
Context webContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource) webContext.lookup("jdbc/nameofmyjdbcresource");

For SQLServer:
SQLServerConnectionPoolDataSource ds = new SQLServerConnectionPoolDataSource();
ds.setURL("jdbc:sqlserver://host:1433;databaseName=db");


Expose the JNDI name to the Web application
(
https://glassfish.dev.java.net/javaee5/ejb/compdependencies_xmlforum_nov15.pdf),
by Adding a 'resource-ref' element in web.xml like this:


  1. <resource-ref>
  2.     <res-ref-name>mail/initurfms </res-ref-name>
  3.     <res-type>javax.mail.Session </res-type>
  4.     <res-auth>Container </res-auth>
  5. </resource-ref>
Adding a 'reference-descriptor' element in weblogic.xml:
   
  1. <reference-descriptor>
  2.   <resource-description>
  3.     <res-ref-name>mail/initurfms </res-ref-name>
  4.     <jndi-name>mail/initurfms </jndi-name>
  5.   </resource-description>
  6. </reference-descriptor>
If you run your application in Weblogic, you don't need to create these two xml files, instead you can
configure the connectionpool, datasource directly in weblogic console. see JUnit关于数据库访问的单元测试 (2) --------------------------------
-------------------------------------------------------------------------------------------------------------

Another approach to unit test the datasource without the context:
using the class oracel.jdbc.xa.client.OracleXADataSourc

A factory for XAConnection objects. An object that implements the
XADataSource interface is typically registered with a JNDI service provider.
For optimization purposes, we implemented 2 versions of OracleXADataSource:
one for client, and one for server when used in Java Stored Procedures and
in EJB. The server-version is only available in 8.1.6 and post-8.1.6 backends.
This one is the implementation of OracleXADataSource for client-side usage
and works for both pre- and post-8.1.6 RMs.


public static DataSource createContractDataSource() throws SQLException {
OracleXADataSource dataSource;
dataSource = new OracleXADataSource();

dataSource.setUser(Configuration.getConfigurationProperty(Configuration.SKEL_DATABASE_USERNAME));

dataSource.setPassword(Configuration.getConfigurationProperty(Configuration.SKEL_DATABASE_PASSWORD));

dataSource.setURL(Configuration.getConfigurationProperty(Configuration.SKEL_DATABASE_URL));

Properties properties = new Properties();
properties.put("someproperty", "value");

dataSource.setConnectionProperties(properties);
return dataSource;
}

public class Configuration {

/** Configuration File Name. */
public static final String CONFIGURATION_FILE_NAME = "configuration.properties";

/** Skeleton Database Username. */
public static final String SKEL_DATABASE_USERNAME = "database.username";

/** Skeleton Database Password. */
public static final String SKEL_DATABASE_PASSWORD = "database.password";

/** Skeleton Database URL. */
public static final String SKEL_DATABASE_URL = "database.url";

private static Properties configuration = null;

private Configuration() {
//private so we can't instantiate the class
}


public static String getConfigurationProperty(String property) {
if (configuration == null) {
try {
loadConfiguration();
} catch (IOException e) {
//TODO error loading file, handle it better than this.
return null;
}
}

return configuration.getProperty(property);
}

private static void loadConfiguration() throws IOException {
configuration = new Properties();
InputStream input = ClassLoader.getSystemClassLoader().getResourceAsStream(
CONFIGURATION_FILE_NAME);

if (input == null) {
throw new FileNotFoundException(CONFIGURATION_FILE_NAME + " is not on the classpath");
}

configuration.load(input);
}

}

已经博主授权,源码转载自 https://pan.quark.cn/s/a4b39357ea24 在信息技术领域,特别是软件编程行业,微软公司推出的集成开发环境(IDE)Visual Studio,凭借其卓越的功能和广泛的适用范围,成为了众多程序员的常用工具。不过,在实际操作期间,用户可能会遭遇各种挑战,其中一种较为普遍的挑战是“Visual Studio遭遇了异常情况,这或许与某个附加组件有关”。本文将详细研究这一现象的成因、潜在后果以及最终的应对措施。 ### 原因剖析 Visual Studio通过支持多种插件和附加组件来扩展其功能,这些组件通常由第三方开发者设计,旨在为用户提供更多个性化和专业化的工具。然而,这些插件的质量良莠不齐,部分可能未经过充分的测试或与特定版本的Visual Studio存在兼容性难题,从而在执行时引发异常。异常的出现可能源于以下几个因素: 1. **代码缺陷**:若附加组件中的代码存在逻辑问题或资源管理不当,就可能导致运行时异常。 2. **资源竞争**:多个插件同时占用相同的资源(例如内存、文件句柄等),可能会产生资源冲突,进而触发异常。 3. **依赖不匹配**:插件可能需要特定版本的库或框架,如果系统中安装的版本不一致,也可能导致异常。 4. **安全隐患**:部分插件可能存在安全漏洞,一旦被恶意利用,可能会导致更严重的问题,包括但不限于异常崩溃。 ### 后果分析 当Visual Studio遇到由附加组件引发的异常时,不仅会中断当前的工作进程,降低开发效能,还可能带来以下潜在风险: 1. **数据遗失**:若异常发生在保存操作之前,可能会导致未保存的工作内容遗失。 2. **稳定性减弱**:频繁的异常会导致Visual Stud...
内容概要:本文围绕有源中点箝位(ANPC)三电平并网逆变器,提出并深入研究了一种融合双极性倍频脉宽调制(DPWMA)、正负序分离锁相控制与电网电压前馈控制的高性能一体化并网策略。研究首先系统分析了ANPC三电平逆变器在开关损耗均衡、中点电位稳定、输出谐波含量低等方面的拓扑结构优势,为实现高质量并网奠定了坚实的硬件基础。在此基础上,通过引入DPWMA调制策略,有效提升了等效开关频率,显著优化了输出电压电流的波形质量,降低了谐波畸变。为应对电网电压不平衡、畸变等复杂工况,研究采用了正负序分离锁相技术,实现了对电网正序和负序分量的精确分离与独立控制,从而保障了在非理想电网条件下的精准相位同步。同时,通过叠加电网电压前馈控制,构建了前馈-反馈复合控制体系,提前补偿电网扰动,极大地增强了系统的动态响应速度和抗干扰能力。最终,通过Simulink仿真平台对稳态、电网不平衡及动态扰动等多种工况进行了全面验证,结果表明该复合控制策略能显著提升并网系统的电能质量、稳定性和工况适应性,为新能源发电等大功率并网应用提供了先进的技术解决方案。; 适合人群:具备电力电子、自动控制理论或新能源并网技术等相关专业知识背景,从事相关领域科研或工程开发工作的研究人员,尤其适合高校研究生、青年教师及电力系统仿真与设计工程师。; 使用场景及目标:①应用于对电能质量要求严苛的大功率并网逆变器控制系统设计与优化;②解决电网电压不平衡、谐波畸变等复杂非理想工况下的并网稳定性与同步精度问题;③为ANPC三电平逆变器的先进控制策略开发与性能提升提供详尽的仿真验证方案和技术参考;④支持高水平科研论文的复现、学位论文的课题研究以及重大工程项目前期的技术预研与论证。; 阅读建议:建议读者结合文中详述的系统拓扑、控制架构图及仿真模型,循序渐进地理解各控制模块的设计原理与协同工作机制,重点关注DPWMA调制的实现细节、正负序分离的数学原理与实现方法,以及前馈控制的嵌入方式与参数整定策略,并通过仿真实验与传统控制策略进行对比分析,以深刻掌握该复合控制策略的性能优势与工程应用价值。
内容概要:本文围绕“爆破载荷参数”主题,基于UFC 3-340-02与TM 5-855-02标准,系统研究爆炸冲击波在空气中的传播规律及其压力效应的理论建模与数值仿真方法,并通过Matlab代码实现关键参数的计算与分析。研究聚焦于峰值超压、正压持续时间、冲量等核心爆炸参数的工程估算模型,结合经验公式与简化物理假设,构建适用于防护结构设计与毁伤评估的爆炸载荷输入模型。重点在于将复杂的爆炸物理过程转化为可编程的数学表达式,利用Matlab平台完成数据可视化、参数敏感性分析及多工况仿真对比,从而为军事防护工程、建筑抗爆设计等领域提供科学依据和技术支持。; 适合人群:具备一定Matlab编程能力与力学基础知识,从事安全工程、防护结构设计、爆炸力学、武器效应分析及相关领域的科研人员、工程师与高校研究生。; 使用场景及目标:①掌握UFC/TM标准中爆炸压力参数的工程计算原理与应用方法;②学习如何将爆炸力学理论模型转化为可执行的Matlab代码;③应用于爆炸载荷下结构动力响应仿真、毁伤效能评估、安全距离判定等科研与工程实践任务; 阅读建议:建议读者结合UFC 3-340-02原始文献进行对照学习,重点关注代码中物理公式的单位一致性与参数量纲处理,动手调试并扩展代码以深入理解爆炸波传播特性,并尝试将其应用于多因素耦合(如地形、障碍物)的实际场景仿真中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值