繁体   English   中英

为什么在测试类中设置的 spring.profiles.active 在实际测试类的环境属性中不可用?

[英]Why is spring.profiles.active set in test class not available in environment property of the actual class under test?

我可以通过在测试类上设置 @ActiveProfiles 来访问我尝试测试的类中的 environment.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");
   }

}

您无法使用environment.getProperty("spring.profiles.active")访问活动配置文件,有特定的Environment#getActiveProfiles方法返回显式为此环境激活的配置文件集。 因此,如果您在类中自动装配了ApplicationContext ctx ,则可以获得如下所示的活动配置文件集:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM