SpringTest框架JUnit单元测试用例获取ApplicationContext实例的方法
来源:互联网 发布:淘宝买家手机号码采集 编辑:程序博客网 时间:2024/06/06 01:34
方法一
定义一个工具类:Spring Bean中如何获取ApplicationContext
方法二
from: http://www.coderli.com/junit-spring-test-applicationcontext/
JUnit单元测试用例中使用Spring框架,之前我的使用方式很直接。
/** * 用于需要用到Spring的测试用例基类 * * @author lihzh * @alia OneCoder * @blog http://www.coderli.com */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = { "/spring/applicationContext.xml" })public class SpringTest {}
在测试的过程中,有人提到,想要获取ApplicationContext实例。于是,添加了对ApplicationContext的注入。
/** * 用于需要用到Spring的测试用例基类 * * @author lihzh * @alia OneCoder * @blog http://www.coderli.com */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = { "/spring/applicationContext.xml" })public class SpringTest {@Autowiredprotected ApplicationContext ctx;
其实,Spring中早已直接提供了更加方便使用的基类:
AbstractJUnit4SpringContextTests。修改代码如下:
/** * 用于需要用到Spring的测试用例基类 * * @author lihzh * @alia OneCoder * @blog http://www.coderli.com */@ContextConfiguration(locations = { "/spring/applicationContext.xml" })public class SpringTest extends AbstractJUnit4SpringContextTests {public <T> T getBean(Class<T> type) {return applicationContext.getBean(type);}public Object getBean(String beanName) {return applicationContext.getBean(beanName);}protected ApplicationContext getContext() {return applicationContext;}}
代码也简洁多了。
现在想想,你想要的常用功能,一般人家都能想到了。做之前,不妨先查查有没有现成可用的工具吧:)
阅读全文
0 0
- SpringTest框架JUnit单元测试用例获取ApplicationContext实例的方法
- SpringTest框架JUnit单元测试用例获取ApplicationContext实例的方法
- SpringTest框架JUnit单元测试用例获取ApplicationContext实例的方法
- 单元测试代码:SpringTest+JUnit
- 单元测试代码:SpringTest+JUnit
- SpringTest框架整合JUnit单元测试两种方式
- JUnit单元测试框架的使用
- JUnit单元测试框架的使用
- JUnit单元测试框架的使用
- JUnit单元测试框架的使用
- JUnit单元测试框架的使用
- JUnit单元测试框架的使用
- JUnit单元测试框架的使用
- Spring框架下的Junit单元测试
- Junit单元测试框架的基本使用
- 关于junit单元测试框架的使用
- SpringBoot框架下基于Junit的单元测试
- Android单元测试(一):JUnit框架的使用
- c语言之指针和数组(一)
- thinkphp怎么显示当前服务器的地址_SERVER["SERVER_NAME"]
- jConsole, jVisualvm, btrace 使用体会
- HDU-1688 Sightseeing(最短路+次短路)
- 《图解HTTP》(一)之HTTP基础
- SpringTest框架JUnit单元测试用例获取ApplicationContext实例的方法
- SpringBoot学习(一)SpringBoot基础入门
- CodeForces 815E Karen and Neighborhood题解
- redux(二) 数据流向
- Angular 4.x 修仙之路
- Python——为什么要在意:模块重载
- CodeForces 817E Choosing The Commander题解
- 【经验随笔】 Tomcat多个APP使用相同名称环境变量导致问题
- ThinkPHP 5.0 配置文件