maven依赖java
<!--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>
依赖注入的Beanspring
/** * @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); } }