【问题标题】:Why is spring.profiles.active set in test class not available in environment property of the actual class under test?为什么在测试类中设置的 spring.profiles.active 在实际测试类的环境属性中不可用?
【发布时间】:2021-12-07 22:13:15
【问题描述】:

我能否通过在测试类上设置@ActiveProfiles 来访问我尝试测试的类中的 enviorment.getProperty("spring.profiles.active"),

    @RunWith(SpringJUnit4ClassRunner.class)
    @WebMvcTest(value = TradeController.class)
    @ActiveProfiles("test)
    class TradeControllerTest{
       @Autowired
       private MockMvc mockMvc;
       
    
        @MockBean
        private TradeServiceImpl tradeServiceImpl;
    
        @Mock
        private ConfigurableEnvironment enviroment;
    
        @Before
        public void setup(){
          MockitoAnnotations.initMocks(this);
        }
    
       @Test
        public void test() throws Exception{
          Mockito.doNothing().when(tradeServiceImpl).getAllTrades(any());
          RequestBuilder requestBuilder = MockMvcRequestBuilder.get(new 
              URI("/getTrades")).accept(MediaType.APPLICATION_JSON);
          MvcResult  result = mockMvc.perform(requestBuilder).andReturn(); // calling the 
                                       actual class under test
          assertEquals(result.getResponse().getStatus(), 400);
        }
}

下面是课程,我正在阅读 spring.profiles.active。然而,它即将为空

@RestController
public class TradeController{

  @Autowired
  private TradeServiceImpl tradeServiceImpl; 
 
  @Autowired
  private Environment environment;

  @GetMapping("/getTrade")
  public ResponseEntity<String> getTrade(@PathVariable final String 
    tradeId){
         String profile = environment.getProperty("spring.profiles.active");
   }

}

【问题讨论】:

    标签: spring-boot spring-mvc spring-test


    【解决方案1】:

    您不能使用environment.getProperty("spring.profiles.active") 访问活动配置文件,有一个特定的Environment#getActiveProfiles 方法可以返回为此环境明确激活的配置文件集。因此,如果您在课堂上自动连接 ApplicationContext ctx,您可以获得如下活动配置文件集:

    Environment env = ctx.getEnvironment();
    String[] profiles = env.getActiveProfiles();
    

    【讨论】:

      猜你喜欢
      • 2020-06-08
      • 2019-06-29
      • 1970-01-01
      • 2015-08-09
      • 2017-10-13
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2019-09-06
      相关资源
      最近更新 更多