如何根据弹簧启动中的配置文件运行/关闭选择性测试

bra*_*orm 8 spring spring-test spring-boot

我有一个spring-boot我正在编写IT测试的应用程序.

测试数据来自application-dev.properties我激活dev配置文件时

这是我测试的内容:

@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class ApplicationTests {

    @Autowired
    Environment env;

    @Test
    public void contextLoads() {
        System.out.println(Arrays.toString((env.getActiveProfiles())));

    }

}
Run Code Online (Sandbox Code Playgroud)

ServiceITTest

public class ServiceITTest extends ApplicationTests {


     @value
     String username;

     @value
     String address;

     @Autowired
     MyService myService;


      @Test
      public void check_for_valid_username_address(){
            myService.validate(username,address);
      }
}
Run Code Online (Sandbox Code Playgroud)

我希望上面的测试仅在我设置"dev","qa"的配置文件时运行.默认情况下,它不应该运行.

是否可以在弹簧靴测试中获得精细控制?

Sha*_*ark 7

您可能希望使用@IfProfileValue注释.不幸的是,它不能直接在活动配置文件上工作,但它可以读取属性,因此如果您只在配置文件中定义要运行测试的特定属性,则可以在该特定属性上使用该注释.

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#integration-testing-annotations-junit

  • 您建议的解决方法的示例将非常有帮助。我无法弄清楚这一点。 (2认同)

der*_*itz 5

它也适用于活动配置文件 - 有一个包含活动配置文件的属性值:

仅使用特定配置文件进行测试:

@IfProfileValue(name = "spring.profiles.active", values = {"specific"})
Run Code Online (Sandbox Code Playgroud)

由于我的测试在特定配置文件处于活动状态时不应运行,因此我将其添加到这些测试中:

@ActiveProfiles(profiles = {"default"})
Run Code Online (Sandbox Code Playgroud)

它不适用于@IfProfileValue“默认”,我也没有发现任何“如果特定配置文件未激活则运行”。


Mar*_*ijk 5

在Spring中也可以使用@DisabledIf注解。它允许指定Spring 表达式语言表达式。有关示例,请参阅此博客文章。

JUnit 5 还具有:

  • @DisabledIfEnvironmentVariable
  • @DisabledIfSystemProperty