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

Viewed 293

Will I be able access enviorment.getProperty("spring.profiles.active") in the class that I am trying to test by setting @ActiveProfiles on Test class,

    @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);
        }
}

Below is the class, where I am reading spring.profiles.active. It is however, coming null

@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");
   }

}
1 Answers

You cannot access the active profile with environment.getProperty("spring.profiles.active"), there is the specific Environment#getActiveProfiles method that returns the set of profiles explicitly made active for this environment. So if you autowired your ApplicationContext ctx in your class you can obtain the set of active profiles like below :

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