问题:
今天在使用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 的路径
//修改后的jUnitCase
import 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());
}
}
具体的分析可以看以上的链接的原文。