前言
我这里通过创建 SpringBoot 项目来测试 Junit
这里只对简单配置的 Application Context 和在测试中注入Bean 做演示,以后会更新此博客,会对 Spring 测试做更多的讲述。
示例
1.准备
增加Spring 测试的依赖包到 pom.xml(我这里使用 SpringBoot 创建项目,已经默认引入了相关的依赖),若 pom.xml 中没有相关依赖,可参考如下 依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
2.业务代码
在src/main/java 下的源码:
package zhy;
public class TestBean {
private String content;
public TestBean(String content){
super();
this.content = content;
}
public String getContent(){
return content;
}
public void setContent(String content) {
this.content = content;
}
}
3.配置类
在src/main/java 下的源码:
package zhy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
@Configuration
public class TestConfig {
@Bean
@Profile("dev")
public TestBean devTestBean(){
return new TestBean("from development profile");
}
@Bean
@Profile("prod")
public TestBean prodTestBean(){
return new TestBean("from production profile");
}
}
4.测试
在src/test/java 下的源码:
package zhy;
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;
@RunWith(SpringJUnit4ClassRunner.class)//1
@ContextConfiguration(classes = {TestConfig.class})//2
@ActiveProfiles("prod")//3
public class DemoBeanIntegrationTests {
@Autowired//4
private TestBean testBean;
@Test//5
public void proBeanShouldInject(){
String expected = "from production profile";
String actual = testBean.getContent();
Assert.assertEquals(expected, actual);
}
}
代码解释
- 1.SpringJUnit4ClassRunner 在JUnit环境下提供 Spring TestContext Framework 的功能。
- 2.@ContextConfiguration 用来加载配置 ApplicationContext, 其中 classes 属性用来加载配置类。
- 3.@ActiveProfiles 用来声明活动的 profile。
- 4.可使用普通的 @Autowired 注入Bean。
- 5.测试代码,通过 JUnit 的 Assert 来校验结果是否和预期一致。
5.测试结果
将@ActiveProfiles(“prod”)改为@ActiveProfiles(“dev”),演示测试不能通过的场景如下所示:
总结
集成测试为我们提供了一种无须部署或运行程序来完成验证系统各部分是否能正常协同工作的能力。后期我还会对Spring的 JUnit 单元测定做更多讲述。