使用Junit对Spring进行单元测试实战小结

Demo代码:

Java代码  收藏代码
  1. @RunWith(SpringJUnit4ClassRunner.class)  
  2. @ContextConfiguration(locations = "classpath*:/META-INF/spring/all-beans.xml")  
  3. public class SomeRemoteServiceTest {  
  4.     @Resource(name = "someRemoteService")  
  5.     RemoteService service;  
  6.   
  7.     @Test  
  8.     public void testService() {  
  9.         Param param = new Param();  
  10.         param.setCityId(330100);  
  11.         System.out.println(JsonUtil.toJson(service.doSomething(param)));  
  12.     }  
  13. }  

 几个关键点:

  1. 使用 @RunWith(SpringJUnit4ClassRunner.class)
  2. 使用@ContextConfiguration引入所有使用到bean的配置文件
  3. 使用@Resouce注入程序定义的bean, 一般它都是应用中定义的某个服务类,比如带有@Service("someRemoteService")注解的类
  4. Spring中常用的注解所代表的含义,参考: http://www.cnblogs.com/rhythmK/p/3412549.html

对于单元测试,测试工程应该会是整个工程项目的其中一个子工程,而这个子工程,应该是会对其他子工程有依赖. 如果是maven项目,要在pom.xml中定义对其他兄弟工程的依赖.

在实际项目里,一般单元测试的范围如下:

  1. Service实现类
  2. Dao实现类
  3. 各种工具类,一般是***Util.java
  4. 其它涉及功能相关的类

一个Spring项目的单元测试结构基本是这个样子.

本文出自"lijingshou"博客,转载请务必保留此出处http://lijingshou.iteye.com/blog/2269593

原文地址:https://www.cnblogs.com/ceshi2016/p/6247618.html