前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring、Spring Boot和TestNG测试指南 - @ActiveProfiles

Spring、Spring Boot和TestNG测试指南 - @ActiveProfiles

作者头像
颇忒脱
发布2018-10-19 14:39:48
1.8K0
发布2018-10-19 14:39:48
举报

Github地址

@ActiveProfiles可以用来在测试的时候启用某些Profile的Bean。本章节的测试代码使用了下面的这个配置:

代码语言:javascript
复制
@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

代码语言:javascript
复制
@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

代码语言:javascript
复制
@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配合使用,这里就不举例说明了。

参考文档

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 例子1:不使用ActiveProfiles
  • 例子2:使用ActiveProfiles
  • 总结
  • 参考文档
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档