使用 Spring 2.5 TestContext 测试框架

参考文档:http://www.ibm.com/developerworks/cn/java/j-lo-spring25-test/


1.  添加org.springframework.test-3.0.1.RELEASE-A.jar。

2.  新建test-context.xml

<?xml version="1.0"encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 <!--  引入定义的Spring配置文件 -->

<import resource="classpath:META-INF/spring/application-context.xml"/>

<import resource="classpath:META-INF/spring/database-context.xml"/>

 </beans>

 

3.  新建测试类

extends AbstractTransactionalJUnit4SpringContextTests

在这个类中注入要被测试的service即可。

@ContextConfiguration(locations={"classpath:META-INF/spring/test-context.xml"})

public class MyServiceTest extends

        AbstractTransactionalJUnit4SpringContextTests {

       protected JdbcTemplate jdbcTemplate;

     @Resource(name ="MydataSource")

    public void setDataSource(final DataSource dataSource) {

        this.jdbcTemplate =new JdbcTemplate(dataSource);

    }

     @Autowired

    private MyService myService;

    @Rollback(false)

    @Test //此注解是junit4提供,需加入junit4的Lib

    public void Add() {         //添加对service中add方法的测试代码

              }

    }

4.  测试类中需添加:

protected JdbcTemplate jdbcTemplate;

    @Resource(name ="MydataSource")

    public void setDataSource(final DataSource dataSource) {

        this.jdbcTemplate =new JdbcTemplate(dataSource);

}

否则在系统有多个dataSource时会导致自动注入失败,默认byType。

5.  AbstractTransactionalJUnit4SpringContextTests为了保持数据的清洁会自动回滚,因此在对数据库进行插入和修改操作时数据库中的数据并不会改变。如果想将数据更新提交到数据库中,只需要在test方法上添加@Rollback(false),不让它回滚,就可以达到目的。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值