通常我们使用JUnit进行单元测试的时候,会对数据库记录进行更改操作,破坏数据库现场。比如测试添加数据的时候,你现在添加一条主键ID为1的记录,下次你再添加一条这样的记录就会报错。另外,我们还得手工添加bean,比如:
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"beans.xml");
UserService userService = (UserService) ctx.getBean("userService");
但是如果我们使用Spring测试框架的话,就可以解决这两个问题。因为Spring框架会使用事务回滚,当你测试添加的时候,假如测试成功,你会发现数据库并没有这条记录。而且我们可在测试类中使用注解,这样我们就不用在手工获取bean了。具体使用如下:
(1)、创建一个test资源文件,它下面的包跟你要测试的类一模一样。如图:
把所有测试类放在test根目录,这样不影响项目文件。
(2)导入spring-test-3.2.4.RELEASE.jar和JUnit4.4jar包,(注:我用的是Spring 3.2.4,另外这连个jar包可以不放在lib目录下,自 己建一个目录,因为发布的时候,这两个jar包不需要)。
(3)、在test资源目录下的com.ssh.service.impl中新建一个ServiceTest类(我要测试Service层)
@ContextConfiguration
public class ServiceTest extends AbstractTransactionalJUnit4SpringContextTests{
@Autowired
private UserService userService;
@Test
public void testExists() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"beans.xml");
UserService userService = (UserService) ctx.getBean("userService");
User user = new User();
user.setUsername("zz");
userService.exists(user);
}
@Test
public void testSave() {
User user=new User();
user.setUsername("Spring测试框架");
user.setPassword("Spring测试框架");
userService.add(user);
}
}
上面的testExists方法是只用JUnit测试时的写法,testSave方法是用了Spring测试框架的写法。可以做个比较。用Spring测试框架,首先让测试类继承AbstractTransactionalJUnit4SpringContextTests,然后加上注解,userService通过自动装配,注入得到。
(3)、加上一个ServiceTest-context.xml文件,这个文件与测试类在一个包中,即test下面的com.ssh.service.impl这个包中
ServiceTest-context.xml的内容如下:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<import resource="classpath:/beans.xml"/>
</beans>
注:可能大家会发现我在test资源目录下,又放了一个beans.xml文件。这是因为 <import resource="classpath:/beans.xml"/> ,会从test资源目录造beans.xml,而不是从src下的beans.xml中找。最终测试:
大家可以看到右边的图片,有插入语句,当时紧接着下面有rollback语句,即事务回滚了。
推荐大家参考这篇文章:点击打开链接