如何在项目中进行单元测试,数据源在tomcat上 ,底层封装的dbmanager,在tomcat起来时,直接读取配置的数据源 。咋整????????????
1条回答 默认 最新
- qq_38094834 2018-08-16 10:19关注
解决方案
由于项目集成了Spring的自动注入等功能,所以在使用Junit进行单元测试的时候需要保证Spring的配置文件都能被加载,同时需要保证连接数据库的数据源必须被加载,这就需要配置单独的数据源,具体方法如下:
新建spring_jndi_test.xml
<?xml version="1.0" encoding="UTF-8"?>
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">
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
/beans:bean
/beans:beans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
在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配置结束............."); }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
至此,便可以进行Junit的单元测试,且数据源也能获取了。当然,如果出现“java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver”,那么则需要Build Path -> Add Libraries … 引入ojdbc包即可。
解决 无用评论 打赏 举报
悬赏问题
- ¥15 聚类分析或者python进行数据分析
- ¥15 如何用visual studio code实现html页面
- ¥15 逻辑谓词和消解原理的运用
- ¥15 三菱伺服电机按启动按钮有使能但不动作
- ¥15 js,页面2返回页面1时定位进入的设备
- ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
- ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
- ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
- ¥20 腾讯企业邮箱邮件可以恢复么
- ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?