使用jUnit4测试Spring4
来源:互联网 发布:excel相关系数矩阵 编辑:程序博客网 时间:2024/06/07 12:24
问题:
今天在使用spring框架做项目的时候发现一个问题: 自动注入@Autowired 在jUnit使用没有效果但是使用一般手动注入getBean的方法的时候是有效果的。
起先我以为是jUnit的中不能够自动注入Spring中的对象,折腾了一段时间在网上搜索解决方法,找到了一篇文章
http://blog.csdn.net/shunshoutuya/article/details/17953183,很详细的描述如何整合JUnit和Spring,根据这篇文章我给出我自己简单有效的解决方案。
原jUnitCase写法:添加上@Autowired 主动装配 spring配置文件xml 中实例的 JdbcTemplate 的一个对象
//这种写法是无效的,无法正常注入 import org.junit.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;public class daoimplTest { @Autowired private JdbcTemplate jdbcTemplate; @Test public void jdbcTemplateTest() { System.out.println(jdbcTemplate.getDataSource()); }}
运行junitCase: 结果,提示空指针异常java.lang.NullPointerException
at pers.h.finalproject.test.daoimplTest.jdbcTemplateTest(daoimplTest.java:12)
解决方案:
1、导入架包spring-test-4.1.6.RELEASE.jar
2、更改jUnitCase的写法,添加
@RunWith(SpringJUnit4ClassRunner.class) : 接入Spring
@ContextConfiguration : 指定Spring配置文件 xml 的路径
//修改后的jUnitCaseimport org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration({"classpath:applicationContext.xml"})public class daoimplTest { @Autowired private JdbcTemplate jdbcTemplate; @Test public void jdbcTemplateTest() { System.out.println(jdbcTemplate.getDataSource()); }}
具体的分析可以看以上的链接的原文。
阅读全文
0 0
- 使用jUnit4测试Spring4
- Spring4整合Junit4 测试
- Hibernate4与Spring4整合,使用Junit4测试相关学习笔记
- Spring4.0集成Junit4测试case
- 使用JUnit4测试Spring
- 使用JUnit4测试Spring
- 使用JUnit4测试Spring
- Spring4 + Junit4 实现测试中ApplicationContext的获取
- [SSM]使用spring4+Junit4时发生的Java.lang.ExceptionInInitializerError
- 使用JUnit4测试Spring(转)
- Junit4测试套件的使用
- spring4 +junit4+ThreadPoolTaskExecutor
- spring4.2+SpringDataRedis+Junit4
- Spring4+Hibernate4+junit4环境搭建
- eclipse下使用ant进行junit4测试
- JUnit4 使用注解(元注释)进行测试
- JUnit4 使用注解(元注释)进行测试
- 使用Spring+Junit4.4进行测试
- 初学Vue-cli
- 【计算机视觉】全景相机标定(MATLAB/opencv)
- 关于凸优化的一些简单概念
- 2017上海金马五校程序设计竞赛 O:An Easy Problem
- 面试题29数组中出现次数超过一半的数字
- 使用jUnit4测试Spring4
- 【HDU 1427 计算24点 DFS】
- 两数之和
- 数据结构与算法之线性表(一)(笔记)
- 了解CSS属性font-kerning,font-smoothing,font-variant
- java:控制台输入方法
- 湫湫买火车票 最短路
- JS 小tips
- 【NGUI基础知识】——Scroll View(滚动视图)