Junit单元测试Spring读取classes或者WEB-INF目录下的配置文件

转自 CSDN渐渐老去 原文地址

关于spring-test +junit可以参考:https://www.cnblogs.com/onetwo/p/6370110.html

我的问题是:配置文件在WEB-INF下怎么引入(别问为什么放这个位置,我也很郁闷的)

假设Spring配置文件为spring-context.xml


一、Spring配置文件在类路径下面(maven项目)

在Spring的java应用程序中,一般我们的Spring的配置文件都是放在放在类路径下面(也即编译后会进入到classes目录下)。

因为是用maven管理的,所以配置文件都放在“src/main/resources”目录下这时候,在代码中可以通过

ApplicationContext applicationContext = newClassPathXmlApplicationContext("spring-context.xml");  

或者

 ApplicationContext applicationContext = new FileSystemXmlApplicationContext("classpath:地址");

然后applicationContext.getBean(" ")获取相应的spring管理的bean。

spring4以后提供了对Junit框架的整合即:spring-test +junit的方式

通过注解方式引入spring的配置文件,之后直接在单元测试类中用@Autowired等同类注解注入spring管理的类即可使用

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations={"classpath*:spring-context-xx1.xml"})  
/**
 * classpath*表示class文件路径下任意层级
 * 因为location{}接收一个数组所以当配置文件分开写
 * 并且不是一个总配置文件引入其他配置文件的方式可以采用如下方式写
 */
@ContextConfiguration(locations={"classpath*:spring-context-xx1.xml",
                                 "classpath*:spring-context-xx2.xml"
                                })  

 

二、Spring配置文件在WEB-INF下面(maven项目)

当然在做J2EE开发时,有些人习惯把Spring文件放在WEB-INF目录(虽然更多人习惯放在类路径下面)下面;或者有些Spring配置文件是放在类路径下面,而有些又放在WEB-INF目录下面。这时候,在代码中就不可以使用ClassPathXmlApplicationContext来加载配置文件了,而应使用FileSystemXmlApplicationContext。

ApplicationContext applicationContext = newFileSystemXmlApplicationContext("src/main/webapp/WEB-INF/spring-context.xml");

如果采用跟上面junit+spring注解的方式:


@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring-context.xml"}) 

说明:上面这个location路径是maven工程的WEB-INF的路径,传统web工程如下:


@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations={"file:WebRoot/WEB-INF/spring-context.xml"}) 

下面是一个抽象的Junit测试基类,其它测试类继承此类然后通过注解的方式即可获得spring管理的bean:

package com.junit.test;
 
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
 
@RunWith(SpringJUnit4ClassRunner.class)
#@ContextConfiguration(locations = { "classpath:spring-context.xml" })
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring-context.xml" })
public abstract class AbstractBaseTest extends AbstractTransactionalJUnit4SpringContextTests {
 
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值