我需要在使用环境bean的测试类之一中读取单元测试的属性,但是spring无法创建环境bean。
@RunWith(SpringRunner.class)
@TestPropertySource(locations = "/application-test.properties")
public class CardTest {
@Autowired
Environment environment;
@Test
public void givenPropertyFetchesAndValidatesTheValue() {
String output = environment.getProperty("test");
assertThat(output).isEqualTo("502123");
}
}
错误:
由以下原因引起:org.springframework.beans.BeanInstantiationException:无法实例化[org.springframework.core.env.Environment]:指定的类是接口。
请帮忙
最佳答案
没有模拟环境:将Env bean注入您的TestClass /套件
@RunWith(SpringRunner.class)
@PropertySource("classpath:/application-test.properties")
public class CardTest {
@Autowired
Environment environment;
@Test
public void givenPropertyFetchesAndValidatesTheValue() {
String output = environment.getProperty("test");
}
}
使用模拟:如果您使用的是Mockito或PowerMockito。您始终可以选择在服务/测试中对其进行模拟
public class MyServicetest {
// Define the Environment as a Mockito mock object
@Mock Environment env;
MyService myService;
@Before
public void init() {
// Boilerplate for initialising mocks
initMocks();
// Define how your mock object should behave
when(this.env.getProperty("MyProp")).thenReturn("MyValue");
// Initialise your service
myService = new MyServiceImpl();
// Ensure that your service uses your mock environment
myService.setEnvironment(this.env);
}
@Test
public void shouldDoSomething() {
// your test
}
}
关于java - 无法在SpringRunner中创建环境bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57449210/