使用jUnit4测试Spring4

问题:
今天在使用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());
    }

}

具体的分析可以看以上的链接的原文。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值