@Profile(“dev”):指定开发环境为dev时生效,对应控制器@ActiveProfiles(“dev”)
@RunWith(SpringJUnit4ClassRunner.class):通过spring的测试类来运行
@ContextConfiguration(classes= {TestConfig.class}):加载配置类,替代了在ApplicationContext中创建配置类
@ActiveProfiles(“dev”):指定当前运行环境为dev
测试依赖
<!-- Spring test 支持 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
bean
public class TestBean {
String content;
public TestBean(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
配置类
@Configuration
public class TestConfig {
@Bean
@Profile("dev")
public TestBean devTestBean() {
return new TestBean("dev");
}
@Bean
@Profile("pro")
public TestBean proTestBean() {
return new TestBean("pro");
}
}
@Profile("dev"):指定开发环境为dev时生效 -> @ActiveProfiles("dev")
测试运行
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= {TestConfig.class})
@ActiveProfiles("dev")
public class TestApp {
@Autowired
public TestBean testBean;
@Test
public void test01() {
String expected = "dev";
String actual = testBean.getContent();
Assert.assertEquals(expected, actual);
}
}
@RunWith(SpringJUnit4ClassRunner.class):通过spring的测试类来运行
@ContextConfiguration(classes= {TestConfig.class}):加载配置类,替代了在ApplicationContext中创建
@ActiveProfiles("dev"):指定当前运行环境为dev