- 集成测试一般需要来自不同层的不同对象的交互,如数据库、网络连接、Ioc容器等,集成测试提供了一种无需部署或运行程序来完成验证系统各个部分是否正常协同功能的能力。
- Spring通过Spring TestContext Framework对继承测试提供顶级支持,它不依赖于特定的测试框架,即可用Junit,也可以用TestNG。
- Spring提供了一个SpringJUnit4ClassRunner类,他提供了Spring TestContext Framework的功能。通过@ContextConfiguration来配置ApplicationContext,通过@ActiveProfiles确定活动的profile。
maven依赖
<!--spring test 支持 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
依赖注入的Bean
/**
* @author Kevin
* @description
* @date 2016/7/4
*/
public class TestBean {
private String content;
public TestBean(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
* @author Kevin
* @description
* @date 2016/7/4
*/
@Configuration
public class TestConfig {
@Bean
@Profile("dev")
public TestBean devTestBean(){
return new TestBean("from devlopment profile");
}
@Bean
@Profile("prod")
public TestBean prodTestBean(){
return new TestBean("from production profile");
}
}
测试类
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Kevin
* @description
* @date 2016/7/4
*/
// 在JUNIT环境下提供Spring TestContext Framework的功能
@RunWith(SpringJUnit4ClassRunner.class)
// 用来加载配置文件ApplicationContext,classes用来指定配置类
@ContextConfiguration(classes = {TestConfig.class})
// 用来声明profile范围
@ActiveProfiles("prod")
public class DemoBeanTest {
@Autowired
private TestBean testBean;
@Test
public void prodBeanInject() {
String expect = "from production profile";
String actual = testBean.getContent();
Assert.assertEquals(expect, actual);
}
}