Spring integration tests with profile

前端 未结 5 1816
温柔的废话
温柔的废话 2020-12-07 21:40

In our Spring web applications, we use the Spring bean profiles to differentiate three scenarios: development, integration, and production. We use them to connect to differe

5条回答
  •  执笔经年
    2020-12-07 21:48

    I had a similar problem: I wanted to run all of my integration tests with a default profile, but allow a user to override with a profile that represented a different environment or even db flavor without having to change the @ActiveProfiles value. This is doable if you are using Spring 4.1+ with a custom ActiveProfilesResolver.

    This example resolver looks for a System Property, spring.profiles.active, and if it does not exist it will delegate to the default resolver which simply uses the @ActiveProfiles annotation.

    public class SystemPropertyActiveProfileResolver implements ActiveProfilesResolver {
    
    private final DefaultActiveProfilesResolver defaultActiveProfilesResolver = new DefaultActiveProfilesResolver();
    
    @Override
    public String[] resolve(Class testClass) {
    
        if(System.getProperties().containsKey("spring.profiles.active")) {
    
            final String profiles = System.getProperty("spring.profiles.active");
            return profiles.split("\\s*,\\s*");
    
        } else {
    
            return defaultActiveProfilesResolver.resolve(testClass);
        }
    }
    

    }

    And in your test classes, you would use it like this:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ActiveProfiles( profiles={"h2","xyz"},
    resolver=SystemPropertyActiveProfileResolver.class)
    public class MyTest { }
    

    You can of course use other methods besides checking for the existence of a System Property to set the active profiles. Hope this helps somebody.

提交回复
热议问题