Spring应用的单元测试
版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://tonyaction.blog.51cto.com/227462/84178 |
8.3 Spring应用的单元测试
1)自动装配的测试用例
代码清单1
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tony.web.dao.FooDao;
@Service
public class FooService {
@Autowired
private FooDao dao;
public String save(String name){
if(name == null || "".equals(name))
throw new RuntimeException("Name is null");
return dao.save(name);
}
}
import org.springframework.stereotype.Repository;
@Repository
public class FooDao {
public String save(String name){
return "success";
}
}
import org.springframework.test.
AbstractDependencyInjectionSpringContextTests;
import com.tony.web.service.FooService;
public class MyTest extends AbstractDependencyInjectionSpringContextTests{
protected FooService fooService;
//set方法
public void setFooService(FooService fooService) {
this.fooService = fooService;
}
//指定Spring配置文件的位置
protected String[] getConfigLocations(){
return new String[]{"spring-config-beans.xml"};
}
//测试方法
public void testSave(){
String str = this.fooService.save("Tony");
System.out.print(str);
assertEquals("success", str);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://...>
<context:component-scan base-package="com.tony"/>
</beans>
代码清单1中定义了FooService.java和FooDao.java两个Bean已经使用 @Autowired进行了装配,我们的单元测试类MyTest继承了
AbstractDependencyInjectionSpringContextTests类,配置好fooService的set方法并且指定Spring配置文件的位置后,当测试用例运行时我们需要的fooService会自动注入进来,我们只要在testSave方法中直接使用就可以了,还有两外一种写法
代码清单2
public class MyTest extends AbstractDependencyInjectionSpringContextTests{
protected FooService fooService;
public MyTest(){
//启用直接对属性变量进行注入的机制
this.setPopulateProtectedVariables(true);
}
protected String[] getConfigLocations(){
return new String[]{"spring-config-beans.xml"};
}
public void testSave(){
String str = this.fooService.save("Tony");
System.out.print(str);
assertEquals("success", str);
}
}
代码清单2中我们移除了set方法,增加了一个构造函数,在构造函数中调用父类的方法启用直接对属性变量进行注入的机制。有时我们测试的时候会操作数据库插入一条记录,由于我们不会每次都修改测试的数据,当我们再次插入同样的数据时数据库肯定会要报错了,此时我们需要既能测试又能不让测试的数据在数据库中起作用,Spring就知道我们的这个需要,为我们准备了AbstractTransactionalSpringContextTests这个类。
代码清单3
import org.springframework.test.
AbstractTransactionalSpringContextTests;
import com.tony.web.service.FooService;
public class MyTest extends AbstractTransactionalSpringContextTests{
protected FooService fooService;
public MyTest(){
this.setPopulateProtectedVariables(true);
}
protected String[] getConfigLocations(){
return new String[]{"spring-config-beans.xml"};
}
//测试方法中的数据操作将在方法返回前被回滚,不会对数据库产生永久性数据操作,下一//次运行该测试方法时,依旧可以成功运行.
public void testSave(){
String str = this.fooService.save("Tony");
System.out.print(str);
assertEquals("success", str);
}
}
这样就可以在方法返回之前将测试数据回滚,以保证下次单元测试的成功。
本文出自 “绝缘材料” 博客,请务必保留此出处http://tonyaction.blog.51cto.com/227462/84178 本文出自 51CTO.COM技术博客 |



tony_action
博客统计信息
热门文章
最新评论
友情链接