Spring profiles on integration tests class

2019-09-07 03:25发布

we have selenium tests which are ran by java test class.

On local environment everything is ok, but I want to switch off those tests when run on jenkins.

So I use:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest("server.port=1234")
@Profile("!jenkins")
@ActiveProfiles("integrationtests")
public class LoginAndEditProfileSeleniumTest {
...

What works: running mvn clean test run all tests locally, with integrationtests profile active. I dont want to pass any additional parameter.

What I want to achieve: running mvn clean test -Dspring.profiles.active=jenkins switch off this test.

Can I merge somehow profile passed by parameter, ActiveProfile annotation and take Profile annotation into consideration? :)

//update: Its possible to use class extending ActiveProfilesResolver:

public class ActiveProfileResolver implements ActiveProfilesResolver {
@Override
public String[] resolve(Class<?> testClass) {

    final String profileFromConsole = System.getProperty("spring.profiles.active");
    List<String> activeProfiles = new ArrayList<>();
    activeProfiles.add("integrationtests");
    if("jenkins".contains(profileFromConsole)){
        activeProfiles.add("jenkins");
    }
    return activeProfiles.toArray(new String[activeProfiles.size()]);
}
}

but it seems to not to cooperate with @Profile anyway ( jenkins profile is active but test is still running ) .

1条回答
欢心
2楼-- · 2019-09-07 03:56

@Profile has zero affect on test classes. Thus, you should simply remove that annotation.

If you want to enable a test class only if a given system property is present with a specific value, you could use @IfProfileValue.

However, in your scenario, you want to disable a test class if a given system property is present with a specific value (i.e., if spring.profiles.active contains jenkins).

Instead of implementing a custom ActiveProfileResolver, a more elegant solution would be to use a JUnit assumption to cause the entire test class to be ignored if the assumption fails.

This should work nicely for you:

import static org.junit.Assume.*;

// ...

@BeforeClass
public static void disableTestsOnCiServer() {
    String profilesFromConsole = System.getProperty("spring.profiles.active", "");
    assumeFalse(profilesFromConsole.contains("jenkins"));
}

Regards,

Sam (author of the Spring TestContext Framework)

查看更多
登录 后发表回答