java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Maven中Junit对Spring进行单元测试

Maven项目中Junit对Spring进行单元测试方式

作者:feelThonf

本文介绍了在Spring框架中使用JUnit进行单元测试的方法,包括添加依赖、使用注解、创建测试基类等内容,并详细阐述了如何引入多个配置文件

主要步骤:

1.在工程的pom文件中增加spring-test的依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>

2.使用springframework提供的单元测试

新建测试类,并在该类上加上两个注解:

测试代码如下:

import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:ApplicationContext.xml"})
public class EmpolyeeTest {
    @Autowired
    ApplicationContext ctx; 
    @Test
    public void testEmployee(){
        Employee employee =(Employee) ctx.getBean("employee");
        assertEquals("zhangsan",employee.getName());
    }
}

3.封装基于AbstractJUnit4SpringContextTests的测试基类

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:ApplicationContext.xml"})
public class SpringTest extends AbstractJUnit4SpringContextTests { 
   public <T> T getBean(Class<T> type){
       return applicationContext.getBean(type);
   }
   public Object getBean(String beanName){
       return applicationContext.getBean(beanName);
   }
   protected ApplicationContext getContext(){
       return applicationContext;
   }

然后其他测试类只需要继承该类即可,可以省去每次都要绑定Application对象。

4.当项目变得复杂

其中的spring配置文件被拆分成了多个,这样该如何引入多个配置文件呢?如下:

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = { "classpath*:spring-ctx-service.xml", "classpath*:spring-ctx-dao.xml" })

这样就可以轻松的引入多个spring的配置文件了。

或者配置符合某一个正则表达式的一类文件,如:

 @RunWith(SpringJUnit4ClassRunner.class) 
 @ContextConfiguration(locations = "classpath*:spring-ctx-*.xml") 

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文