@IfProfileValue import set from env variable, test not executing

落花浮王杯 提交于 2019-12-22 17:46:18

问题


As a follow up to Is there any way to conditionally ignore a test with JUnit of Spring?, If I want to do this with @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
{...}

the output of the log is profiles [default] [integration], but testExecute is ignored, what am I missing to get this test to run when I enable integration. I am currently enabling it via setting SPRING_PROFILES_ACTIVE=integration in IDEA's test runner.


回答1:


First: You need to use the SpringJUnit4ClassRunner and use a junit version > 4.9.

The annotation name is a little counter intuitive: It checks a key-value from a ProfileValueSource. By default only the SystemProfileValue source is configured by spring, providing access to the system properties.

You can provide your own ProfileValueSource that checks whether a profile is active and configure it to be used using a ProfileValueSourceConfiguration.

If your use case is to have integration tests separated and you are using Maven, consider using using the failsafe plugin and separate the tests, perhaps even in a different module.

I have a short example, due to the very early phase the test classes need to be considered, it will only work with system properties. Since you stated that you use that anyway, you may be happy with it. For real cases (CI server etc.) you should use a more robust approach like the failsafe plugin and a build system supporting separate integration tests.

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

}
}


来源:https://stackoverflow.com/questions/28372099/ifprofilevalue-import-set-from-env-variable-test-not-executing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!