java - @IfProfileValue 从环境变量导入集,测试未执行

标签 java spring spring-3

作为 Is there any way to conditionally ignore a test with JUnit of Spring? 的后续行动,如果我想用 @IfProfileValue

来做到这一点
@RunWith(SpringJUnit4ClassRunner.class)
... 

@Resource ConfigurableEnvironment env;

@Before
public void env () {
    log.debug( "profiles {} {}", env.getDefaultProfiles(), env.getActiveProfiles());
}

@Test
@IfProfileValue( name = "integration" )
public void testExecute() throws JobExecutionException
{...}

日志的输出是profiles [default] [integration],但testExecute被忽略,当我启用集成时,我缺少什么来运行此测试。我目前通过在 IDEA 的测试运行程序中设置 SPRING_PROFILES_ACTIVE=integration 来启用它。

最佳答案

首先:您需要使用 SpringJUnit4ClassRunner 并使用 junit 版本 > 4.9。

注释名称有点违反直觉:它检查来自 ProfileValueSource 的键值。默认情况下,spring 仅配置 SystemProfileValue 源,提供对系统属性的访问。

您可以提供自己的 ProfileValueSource 来检查配置文件是否处于 Activity 状态,并将其配置为使用 ProfileValueSourceConfiguration 来使用。

如果您的用例是将集成测试分开并且您正在使用 Maven,请考虑使用故障安全插件并将测试分开,甚至可能在不同的模块中。

我有一个简短的示例,由于需要考虑测试类的早期阶段,它仅适用于系统属性。既然你说过无论如何你都会使用它,你可能会对此感到满意。对于实际情况(CI 服务器等),您应该使用更强大的方法,例如故障安全插件和支持单独集成测试的构建系统。

@RunWith(SpringJUnit4ClassRunner.class)
@ProfileValueSourceConfiguration(ProfileTest.ProfileProfileValueSource.class)
@SpringApplicationConfiguration(classes = ProfileTest.class)
//won't work since not added to system properties!
//@ActiveProfiles("integration")
public class ProfileTest
{

@Test
public void contextLoads()
{
}

@IfProfileValue( name = "integration", value = "true")
@Test
public void runInIntegration()
{
    throw new RuntimeException("in integration");
}

@Test
public void runDemo()
{
    System.out.println("DEMO, running always");
}

public static class ProfileProfileValueSource implements ProfileValueSource
{
    @Override
    public String get(String string)
    {
        final String systemProfiles = System.getProperty("spring.profiles.active", System.getProperty("SPRING_PROFILES_ACTIVE", ""));

        final String[] profiles = systemProfiles.split(",");

        return Arrays.asList(profiles).contains(string) ? "true" : null;
    }

}
}

关于java - @IfProfileValue 从环境变量导入集,测试未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28372099/

相关文章:

c# - 将 C# Func<> 移植到 Java- Math Equation

java - 如何避免 swagger codegen 接口(interface)中的默认方法实现?

java - 如何从 CSV header 创建 pojo 类

jsp - 在 Spring 3 中将日历对象绑定(bind)到 3 个下拉框

spring - 使用 <jee :jndi-lookup string inside an instance of PropertyPlaceholderConfigurer

spring - Spring session 范围 Controller 中的 transient 字段

java - 加载 url 而不更改 url

java - 如何根据文件大小保持滚动日志文件?

spring - Web 应用程序在嵌入式 tomcat 中的运行速度比在独立 tomcat 中快得多

java - 如何在 spring 单元测试中快速模拟服务?