我正在学习如何以“正确的方式”运行@SpringBootTest,但是在我的测试类(在“ src / test / java”目录中)中自动布线遇到问题:
我在“ src / main / java”下的一个包中有一个@Graph批注的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”:即使我尝试执行以下操作,它也仍然为“ null”(“ xxxxxx”是包含Graphs.java文件的程序包的全名):
在测试包的TestConfiguration.java中添加一个@Bean。
@Bean
public Graphs graph () {
return new Graphs();
}
我开始怀疑我从根本上对设置Spring Boot测试环境有误解/错过了一些东西:难道我只需要@SpringBootTest吗?
答案 0 :(得分:0)
您忘记在@RunWith(SpringRunner.class)
上方添加GraphTest
。
SpringRunner
是SpringJUnit4ClassRunner
的别名,它尤其负责负载TestContextManager
(请参见docs)。没有它,您的应用程序上下文将无法加载进行测试。