Search code examples
spring-bootrediscontinuous-integrationspring-boot-testrate-limiting

Active profile in SpringBootTest based on system variable


As the host of Redis is different in local and CI, my @Tests can pass locally, they can't pass in CI.

Firstly, I tried to mock the RedisTemplate like this:

RedisTemplate redisTemplate = mock(RedisTemplate.class);
ValueOperations valueOperations = mock(ValueOperations.class);
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
when(valueOperations.increment(anyString(), anyLong())).thenReturn(1L);
when(valueOperations.get("[email protected]")).thenReturn("1");

It did mocked RedisTemplate, but can't mock redisTemplate.opsForValue() and valueOperations.increment(...) ( I can't find reason )

Then, I wrote two profiles named application-ci-test.yml and applicaiton-test.yml, tried to active one of them based on system environment variable

I learnd from here that I can set active profile in this way:

@Configuration
public class MyWebApplicationInitializer 
  implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        servletContext.setInitParameter(
          "spring.profiles.active", "dev");
    }
}

and this way:

@Autowired
private ConfigurableEnvironment env;
...
env.setActiveProfiles("someProfile");

But I don't know how to use them. The system variable can get by System.getenv(..). So now I want to know how to active profile based on the variable I get.


Solution

  • I found a way to active corresponding profile based on system variable or property:

    import org.springframework.test.context.ActiveProfilesResolver;
    
    public class SpringActiveProfileResolver implements ActiveProfilesResolver {
        @Override
        public String[] resolve(Class<?> testClass) {
            final String isCITest = System.getEnv("isCITest");
            return new String[] { isCITest == null ? "test" : "ci-test" };
        }
    } 
    

    then use the parameter resolver in @ActiveProiles:

    @ActiveProfiles(resolver = SpringActiveProfileResolver.class)
    

    How to set environment variable is anther issue, and answers above have already answered it