【发布时间】:2019-07-31 00:08:09
【问题描述】:
我正在学习如何以“正确的方式”运行@SpringBootTest,但在我的测试类(在“src/test/java”目录中)中遇到了自动装配问题:
我在“src/main/java”下的包中有一个由@Component注释的类Graphs:
@Component
public class Graphs {
....
}
然后,我在“src/test/java”下创建了测试类。其中之一是:
@SpringBootTest
public class GraphsTest {
@Test
public void testRun () {
Graphs graph = new Graphs(); // Using new to create an object
if (graph==null) {
System.out.println("It's null");
} else {
System.out.println("It's not null");
}
}
...
当我测试运行“testRun”方法时,它按预期产生了“It's not null”。
在单元测试之后,我想注入一个“图”,因为 Graphs 类由 @Component 注释,因此一个 bean 应该可用于自动装配:
@SpringBootTest
public class GraphTest {
@Autowired
private Graphs graph; // auto inject a bean graph
@Test
public void testRun () {
if (graph==null) {
System.out.println("it's null");
} else {
System.out.println("it's not null");
}
}
....
现在使用自动装配,“testRun”总是产生:“it's null”,即使我尝试以下操作,(“xxxxxx”是包含 Graphs.java 文件的包的全名):
- 添加@Import(xxxxxx/Graphs.class)
- 添加@ComponentScan("xxxxxxx")
- 将 Graphs.java 文件复制到测试包中
-
在测试包的TestConfiguration.java中添加@Bean。
@Bean public Graphs graph () { return new Graphs(); }
我开始怀疑我从根本上误解/错过了有关设置 Spring Boot 测试环境的一些东西:这不是我需要开始的全部 @SpringBootTest 吗?
【问题讨论】:
标签: spring-boot autowired spring-boot-test