一个简单的Spring测试的例子


在做测试的时候我们用到Junit Case,当我们的项目中使用了Sring的时候,我们应该怎么使用spring容器去管理我的测试用例呢?现在我们用一个简单的例子来展示这个过程。

  • 1 首先我们新建一个普通的java项目,引入要使用的几个jar包。
    spring测试类的要用的jar包:
    1.spring-test-3.2.4.RELEASE.jar
    spring的核心jar包:
    1.spring-beans-3.2.4.RELEASE.jar
    2.spring-context-3.2.4.RELEASE.jar
    3.spring-core-3.2.4.RELEASE.jar
    4.spring-expression-3.2.4.RELEASE.jar
    spring的依赖jar包:
    1.commons-logging-1.1.1.jar

  • 2新建一个HelloWord类,包含一个公有的sayHelloWord方法,我们的测试主要就是测试这个类的方法:
    package Domain;

      public class HelloWord {
      
      	/**
      	 * 
      	* @Description: 方法 (这里用一句话描述这个类的作用)
      	* @author Jack 
      	* @date 2016年6月15日 下午3:27:43
      	 */
      	public void sayHelloWord(){
      		System.out.println("Hello Word .....");
      	}
      }
    
  • 3 引入spring配置文件applicationContext.xml,配置bean

  • 4 创建junit case 进行测试
    package Test;

      import static org.junit.Assert.*;
      
      import org.junit.Test;
      import org.springframework.context.ApplicationContext;
      import org.springframework.context.support.ClassPathXmlApplicationContext;
      
      import Domain.HelloWord;
      
      public class HelloWordTest {
      
      	@Test
      	/**
      	 * 
      	* @Description: 普通的单元测试(这里用一句话描述这个类的作用)
      	* @author Jack 
      	* @date 2016年6月15日 下午4:33:53
      	 */
      	public void test() {
      		HelloWord domain=new HelloWord();
      		domain.sayHelloWord();
      	}
      
      	@Test
      	/**
      	 * 
      	* @Description: 加载spring容器获得bean进行测试 (这里用一句话描述这个类的作用)
      	* @author Jack 
      	* @date 2016年6月15日 下午4:34:19
      	 */
      	public void testSpring(){
      		ApplicationContext ctx=new ClassPathXmlApplicationContext("resource/applicationContext.xml");
      		HelloWord word=(HelloWord) ctx.getBean("helloWord");
      		word.sayHelloWord();
      		
      	}
      }
    

上面测试用例中,一个是常规的方式(通过主动创建实例对象方式)的测试,一个是通过加载spring容器的方式获得容器提供的实例进行测试。
然而上述所说的方式却存在两个问题:
1.每一个测试都要重新启动spring容器
2.测试的代码在管理spring容器(与我们的目的相反)
为了达到目的我们就要用到spring-test-3.2.4.RELEASE.jar这个jar包里提供的方法去实现。测试的代码如下:

package Test;

import static org.junit.Assert.*;

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;

import Domain.HelloWord;
//告诉spring容器运行在虚拟机中
@RunWith(SpringJUnit4ClassRunner.class)
//配置文件的位置
//若当前配置文件名=当前测试类名-context.xml 就可以在当前目录中查找@ContextConfiguration()
@ContextConfiguration("classpath:resource/applicationContext.xml")
public class SpringHelloWordTest {
	@Autowired
	//自动装配
	private ApplicationContext cxf;
	@Test
	public void test() {
		HelloWord word=(HelloWord) cxf.getBean("helloWord");
		word.sayHelloWord();
	}

}

上述就是整个简单的Spring测试例子大体过程。

原文地址:https://www.cnblogs.com/ITer-jack/p/5588366.html