小编Jia*_*HAI的帖子

基于系统变量的 SpringBootTest 中的活动配置文件

由于Redis的宿主机local和CI不同,我的@Tests可以本地通过,CI不能通过。

首先,我试图模拟RedisTemplate这样的:

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("a@a.com")).thenReturn("1");
Run Code Online (Sandbox Code Playgroud)

它确实被嘲笑RedisTemplate,但不能嘲笑redisTemplate.opsForValue()valueOperations.increment(...)(我找不到原因)

然后,我写了两个名为application-ci-test.ymland 的配置文件applicaiton-test.yml,尝试根据系统环境变量激活其中一个

我从这里了解到我可以通过这种方式设置活动配置文件:

@Configuration
public class MyWebApplicationInitializer 
  implements WebApplicationInitializer {

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

        servletContext.setInitParameter(
          "spring.profiles.active", "dev");
    }
}
Run Code Online (Sandbox Code Playgroud)

这样:

@Autowired
private ConfigurableEnvironment env;
...
env.setActiveProfiles("someProfile");
Run Code Online (Sandbox Code Playgroud)

但我不知道如何使用它们。系统变量可以通过System.getenv(..). 所以现在我想知道如何根据我得到的变量激活配置文件。

continuous-integration rate-limiting redis spring-boot spring-boot-test

5
推荐指数
1
解决办法
4656
查看次数