java - 无法在SpringRunner中创建环境bean

标签 java springrunner

我需要在使用环境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/

相关文章:

java - Mac OS X 上 Java 的 future

java - Gradle 与在同一线程中运行的同一类的方法并行运行测试类

java - 查找文件,对它们进行 gtar 并创建报告

java - 我想在我的小程序中添加计时器

java - 找不到无限循环

java - 在单元测试中使用 SpringRunner 可以吗?

java - 尝试使用 SpringRunner 进行单元测试时出现 NullPointer 异常

java - 编写 JUnit 测试用例时使用 SpringRunner 而不使用 SpringContext 是一个好习惯吗?

java - Dijkstra算法中的无限循环?