【问题标题】:Spring testing framework - JNDI resourceSpring 测试框架 - JNDI 资源
【发布时间】:2012-08-16 23:45:08
【问题描述】:

我正在玩弄 Spring 测试框架,但我有一个问题。通常,当应用程序部署在 Tomcat 上时,我们有

<Resource
       name="jdbc/sqliteDS"
       auth="Container"
       type="javax.sql.DataSource"
       maxActive="4"
       maxIdle="2"
       username="x"
       maxWait="5000"
       driverClassName="org.sqlite.JDBC"
       password="x"
       url="jdbc:sqlite:/home/xxx/db.sqlite"/> 

</Context>

在 Tomcat context.xml 中,

<resource-ref>
    <description>sqlite DataSource</description>
    <res-ref-name>jdbc/sqliteDS</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

在 web.xml 和

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:/comp/env/jdbc/sqliteDS" />
</bean>

在 data-context.xml 中 用于获取数据源,但是如何为 Spring 测试框架模拟 JNDI 资源,因为现在在初始化期间我收到错误,即找不到数据源,他是对的。

此外,如果无需编写另一个 .xml 文件就可以做到这一点,那就太好了。

【问题讨论】:

标签: spring jndi spring-test


【解决方案1】:

前段时间我不得不处理这个问题,但我没有找到合适的解决方案,但是一个暗示另一个 xml 文件的解决方法:

首先,您创建一个定义 JNDI 信息 (jndi.xml) 的 Spring 配置文件:

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

  <bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
    <property name="url" value="jdbc:oracle:thin:@server:port:instance" />
    <property name="username" value="user" />
    <property name="password" value="pwd" />
  </bean>
</beans>

然后是一个静态类来绑定你的 JNDI 变量:

public class Initialize {
    public static void initializeJndi() throws Exception {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("jndi.xml");
        SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
        builder.bind("java:comp/env/jdbc/foo", applicationContext.getBean("dataSource"));
        builder.activate();
    }
}

然后在您的测试类中,添加以下内容:

    @BeforeClass
    public static void initJndi() throws Exception {
        Initialize.initializeJndi();
    }

这样当你加载 Spring 主配置文件时,JNDI 资源就可以访问了。

也许这不是最好的方法,但它确实有效。

顺便说一句,拥有一个特定的配置文件似乎是个好主意,因为您可能不想在最终数据库上运行单元测试。这样做更多地被视为集成测试而不是单元测试。

希望对你有帮助,

嬷嬷

【讨论】:

  • 首先,感谢您的回复。关于单元/集成测试,我想为一个使用Spring容器查找注释类等的类编写一个测试,所以我需要加载所有上下文,为此我需要数据源。
猜你喜欢
  • 1970-01-01
  • 2016-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
  • 1970-01-01
  • 2016-06-06
  • 1970-01-01
相关资源
最近更新 更多