Spring项目中使用Junit单元测试并配置数据源的问题
一、问题描述
由于公司项目中的数据源是配置在Tomcat中的server.xml中的,所以在使用Junit进行单元测试的时候,无法获取数据源。
二、解决方案
由于项目集成了Spring的自动注入等功能,所以在使用Junit进行单元测试的时候需要保证Spring的配置文件都能被加载,同时需要保证连接数据库的数据源必须被加载,这就需要配置单独的数据源,具体方法如下:
-
新建spring_jndi_test.xml
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <beans:property name="driverClassName" value="oracle.jdbc.OracleDriver" /> <beans:property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:sjk" /> <beans:property name="username" value="username" /> <beans:property name="password" value="password" /> </beans:bean> </beans:beans>
-
在Junit测试类中加载配置文件与获取Bean
public class CommonDAOJdbc_StandardTest { private volatile static BeanFactory factory; @Test public void testGetFirmCanOutBalance() { // 获取Bean CommonDAO commonDAO = (CommonDAO) factory.getBean("commonDAO"); // 此处可调用CommonDAO类中的方法 } @Before public void init() { System.out.println("加载spring配置开始 ............"); ArrayList<String> list = new ArrayList<String>(); list.add("spring.xml"); // 将Sprint配置文件加入待加载列表 list.add("Spring_jndi_test.xml"); // 将测试用的数据源配置文件加入待加载列表 try { factory = new ClassPathXmlApplicationContext(list.toArray(new String[list.size()])); // 保证虚拟机退出之前 spring中singtleton对象自定义销毁方法会执行 ((AbstractApplicationContext) factory).registerShutdownHook(); } catch (Exception e) { e.printStackTrace(); System.out.println("加载配置文件时发生错误" + e); } System.out.println("加载spring配置结束............."); } }
至此,便可以进行Junit的单元测试,且数据源也能获取了。
当然,如果出现“java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver”,那么则需要Build Path -> Add Libraries … 引入ojdbc包即可。