为什么 environment.getProperty( "spring.profiles.active" ) 在使用@ActiveProfiles的测试中激活配置文件时返回空值



如果我在测试中用@ActiveProfiles激活一个配置文件,说@ActiveProfiles("test"),并在测试中声明@Mock private ConfigurableEnvironment环境,我将能够检索environment. getproperty ("spring.profiles.active")。我得到的值是null

示例测试如下

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(value = ProductController.class)
@ActiveProfiles("test)
class ProductControllerTest{
@Autowired
private MockMvc mockMvc;

@MockBean
private ProductServiceImpl productServiceImpl;

@Mock
private ConfigurableEnvironment enviroment;

@Before
public void setup(){
MockitoAnnotations.initMocks(this);
}

@Test
public void test() throws Exception{
String profile = environment.getProperty("spring.profiles.active"); // -> This returns null ...why ? If i am setting ActiveProfile as test ..why does above return null?
}
}

ConfigurableEnvironment环境在这里被模拟,因此您将无法使用它检索任何值。请使用实际bean:

@Autowired
private ConfigurableEnvironment enviroment;

Mockito mock用于需要提供虚拟值的场景。请参考:https://www.baeldung.com/mockito-annotations了解如何使用mock。

最新更新