您的位置:首页 > 编程语言 > Java开发

使用 Spring 2.5 TestContext 测试框架

2013-11-14 13:49 288 查看
参考文档: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),不让它回滚,就可以达到目的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: