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

Demo代码:

 

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:/META-INF/spring/all-beans.xml")
public class SomeRemoteServiceTest {
    @Resource(name = "someRemoteService")
    RemoteService service;

    @Test
    public void testService() {
        Param param = new Param();
        param.setCityId(330100);
        System.out.println(JsonUtil.toJson(service.doSomething(param)));
    }
}

 几个关键点:

  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

猜你喜欢

转载自lijingshou.iteye.com/blog/2269593