Github地址
@ActiveProfiles可以用来在测试的时候启用某些Profile的Bean。本章节的测试代码使用了下面的这个配置:
@Configuration
public class Config {@Bean@Profile("dev")public Foo fooDev() {return new Foo("dev");}@Bean@Profile("product")public Foo fooProduct() {return new Foo("product");}@Bean@Profile("default")public Foo fooDefault() {return new Foo("default");}@Beanpublic Bar bar() {return new Bar("no profile");}}
例子1:不使用ActiveProfiles
在没有@ActiveProfiles的时候,profile=default和没有设定profile的Bean会被加载到。
源代码ActiveProfileTest:
@ContextConfiguration(classes = Config.class)
public class ActiveProfileTest extends AbstractTestNGSpringContextTests {@Autowiredprivate Foo foo;@Autowiredprivate Bar bar;@Testpublic void test() {assertEquals(foo.getName(), "default");assertEquals(bar.getName(), "no profile");}}
例子2:使用ActiveProfiles
当使用了@ActiveProfiles的时候,profile匹配的和没有设定profile的Bean会被加载到。
源代码ActiveProfileTest:
@ContextConfiguration(classes = Config.class)
[@ActiveProfiles][doc-active-profiles]("product")
public class ActiveProfileTest extends AbstractTestNGSpringContextTests {@Autowiredprivate Foo foo;@Autowiredprivate Bar bar;@Testpublic void test() {assertEquals(foo.getName(), "product");assertEquals(bar.getName(), "no profile");}}
总结
在没有@ActiveProfiles的时候,profile=default和没有设定profile的Bean会被加载到。
当使用了@ActiveProfiles的时候,profile匹配的和没有设定profile的Bean会被加载到。
@ActiveProfiles同样也可以和@SpringBootTest配合使用,这里就不举例说明了。
参考文档
Spring Framework Testing
Spring Boot Testing