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); } }