【问题标题】:@Autowired failed under @SpringBootTest@Autowired 在@SpringBootTest 下失败
【发布时间】: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 文件的包的全名):

  1. 添加@Import(xxxxxx/Graphs.class)
  2. 添加@ComponentScan("xxxxxxx")
  3. 将 Graphs.java 文件复制到测试包中
  4. 在测试包的TestConfiguration.java中添加@Bean。

    @Bean public Graphs graph () { return new Graphs(); }

我开始怀疑我从根本上误解/错过了有关设置 Spring Boot 测试环境的一些东西:这不是我需要开始的全部 @SpringBootTest 吗?

【问题讨论】:

    标签: spring-boot autowired spring-boot-test


    【解决方案1】:

    您忘记在GraphTest 上方添加@RunWith(SpringRunner.class)

    SpringRunnerSpringJUnit4ClassRunner 的别名,它负责加载TestContextManager(参见docs)。没有它,您的应用程序上下文将不会被加载以进行测试。

    【讨论】:

    • 想澄清一下:您的意思是“没有它,您的应用程序上下文将不会被加载以进行测试”?
    • 这给我带来了另一个头痛:当我使用@RunWith(SpringRunner.class) 时,我得到了“InitializationError”。我刚才单独发布了这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    相关资源
    最近更新 更多