@IfProfileValue import set from env variable, test fails

How does it follow Is there a way to conditionally ignore a test using JUnit 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 logs are from profiles [default] [integration] , but testExecute ignored, which is not enough for me to run this test when I turn on integration. I can currently enable it by setting SPRING_PROFILES_ACTIVE=integration to the IDEA tester.

+1
java spring spring-3
source share
1 answer

First: you need to use SpringJUnit4ClassRunner and use junit version> 4.9.

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

You can provide your own ProfileValueSource that checks to see if a profile is active and configure it to use with ProfileValueSourceConfiguration .

If your use case is to separate integration tests and you are using Maven, consider using a secure plug-in and separate tests, perhaps even in another module.

I have a short example: because of the very early phase, it is necessary to take into account the test classes, it will only work with system properties. Since you stated that you are using it anyway, you may be happy with it. For real cases (CI server, etc.) you should use a more reliable approach, for example, a fail-safe plug-in and a build system that support 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; } } } 
+1
source share

All Articles