且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 Spring 测试模拟的 JNDI 数据源?

更新时间:2023-09-21 14:43:28

我通常在单独的文件中定义我的 JNDI 依赖项,例如 datasource-context.xml:

I usually define my JNDI dependencies in seperate file, like datasource-context.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/jee
        http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">

    <jee:jndi-lookup id="dataSource" 
        jndi-name="java:comp/env/dataSource" 
        expected-type="javax.sql.DataSource" />

</beans>

这样我就可以在测试资源中创建另一个文件并定义适合我的测试数据源,例如 datasource-testcontext.xml:

So that in test resources I can create another file and define the test datasource however it suits me, like datasource-testcontext.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        p:driverClassName="org.hsqldb.jdbcDriver"
        p:url="jdbc:hsqldb:hsql://localhost:9001"
        p:username="sa"
        p:password="" /> 

</beans>

然后在我的测试类中,我使用数据源的测试配置而不是依赖 JNDI 的生产配置:

And then in my test class I use the test configuration of the datasource instead of production one that depends on JNDI:

@ContextConfiguration({
    "classpath*:META-INF/spring/datasource-testcontext.xml",
    "classpath*:META-INF/spring/session-factory-context.xml"
})
public class MyTest {

}


如果数据源未在单独的文件中定义,您仍然可以轻松地存根 JNDI 调用返回的对象:


If the data source is not defined in a separate file You can still stub the object returned by JNDI calls easily:

  • like this: Injecting JNDI datasources for JUnit Tests outside of a container
  • or using classes in package org.springframework.mock.jndi, ie. SimpleNamingContextBuilder (there's an example in the javadoc of this calass).