我将能够访问environment . getproperty ("spring.profiles.active")在类中,我试图通过设置@ActiveProfiles测试类,
@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。然而,它是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");
}
}
您不能使用environment.getProperty("spring.profiles.active")
访问活动的概要文件,有特定的Environment#getActiveProfiles
方法返回为该环境显式激活的概要文件集。因此,如果您在课堂上自动连接ApplicationContext
ctx,您可以获得以下活动配置文件集:
Environment env = ctx.getEnvironment();
String[] profiles = env.getActiveProfiles();