如何将Spring配置注入到JUnit5的TestExecutionListener中?

laik7k3q  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(117)

我正在使用JUnit5 + Sping Boot 运行测试。
我已经实现了一个自定义的TestExecutionListener。
我正在尝试将Spring的Environment对象自动连接到这个自定义侦听器。

import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.junit.platform.launcher.TestExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;

@Component
public class MyListener implements TestExecutionListener {

  @Autowired
  Environment env;

  @Override
  public void testPlanExecutionStarted(TestPlan testPlan) {
    System.out.println("Hi!");
  }
}

这是不工作的,我得到的env空。
据我所知,这是因为负责加载此侦听器的是JUnit,而不是Spring。
此外,Spring上下文是在加载该类之后加载的,此时进行注入已经太晚了。
有没有办法实现我想做的事情?
谢谢你

i2byvkas

i2byvkas1#

您可以通过在junit @ExtendWith注解中传递SpringExtension类来实现这一点。
参考编号:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

@ExtendWith(SpringExtension.class)
@TestPropertySource(locations = "classpath:application.properties")
class TestApplicationProperty {

    @Autowired
    private Environment environment;

    @Test
    void contextLoads() {
        assertNotNull(environment);
        assertNotNull(environment.getProperty("spring.platform"));
        assertEquals("testplatform", environment.getProperty("spring.platform"));
    }
}

在我的application.properties中,我有这些属性。

spring.platform: testplatform

注:classpath:application.propertiessrc/test/resources/application.properties

相关问题