3 Star 6 Fork 5

jarchan / spring-test-examples

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
chapter_2_s2_active_profile.md 2.84 KB
一键复制 编辑 原始数据 按行查看 历史
jarchan 提交于 2017-08-24 17:25 . add: @ActiveProfiles examples

Chapter 2: Annotations - @ActiveProfiles

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

  @Bean
  public Bar bar() {
    return new Bar("no profile");
  }

}

例子1:不使用ActiveProfiles

在没有@ActiveProfiles的时候,profile=default和没有设定profile的Bean会被加载到。

源代码ActiveProfileTest

@ContextConfiguration(classes = Config.class)
public class ActiveProfileTest extends AbstractTestNGSpringContextTests {

  @Autowired
  private Foo foo;

  @Autowired
  private Bar bar;

  @Test
  public 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 {

  @Autowired
  private Foo foo;

  @Autowired
  private Bar bar;

  @Test
  public void test() {
    assertEquals(foo.getName(), "product");
    assertEquals(bar.getName(), "no profile");
  }

}

总结

  • 在没有@ActiveProfiles的时候,profile=default和没有设定profile的Bean会被加载到。
  • 当使用了@ActiveProfiles的时候,profile匹配的和没有设定profile的Bean会被加载到。

@ActiveProfiles同样也可以和@SpringBootTest配合使用,这里就不举例说明了。

参考文档

Java
1
https://gitee.com/chanjarster/spring-test-examples.git
git@gitee.com:chanjarster/spring-test-examples.git
chanjarster
spring-test-examples
spring-test-examples
master

搜索帮助