我正在使用JUnit5+Spring 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上下文是在加载该类之后加载的,现在注入已经太晚了。
有没有办法实现我想要做的事情?
谢谢
您可以通过在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.properties
表示src/test/resources/application.properties