【问题标题】:Adding `@SpringBootTest` annotation triggers IntelliJ false positives添加 `@SpringBootTest` 注释会触发 IntelliJ 误报
【发布时间】:2019-11-13 08:31:13
【问题描述】:

所以如果你有一个测试类

class FooControllerIT{
    @Autowired FooController controller;
}

然后你在类中添加一个@SpringBootTest 注释,IntelliJ 声称

无法自动接线。找不到 'FooController' 类型的 bean。

这是一个谎言,因为测试运行和通过都很好。

如果我将@SpringBootTest 注释替换为@Component 注释,则“错误”会消失(当我再次替换@SpringBootTest 注释时会再次出现)。

是什么导致了这种行为?

(我在 Ultimate 2019.1,使用 Spring Boot 2.1.8-RELEASE)

【问题讨论】:

  • 请添加测试类代码。你到底测试了什么?
  • @ValeriyK。没关系。任何真正使用控制器的东西。
  • 是否适用于Spring Boot低版本,例如2.0.3?您是否在测试类的顶部添加了 @RunWith(SpringRunner.class) ?你用的是 testng 还是 junit?
  • @ValeriyK。我们正在使用@ExtendWith(SpringExtension.class)(用于 Junit),但是是的,我确实添加了它。

标签: java spring spring-boot intellij-idea


【解决方案1】:

无法找到您的 Controller 的可能方式是它与注释为 @SpringBootApplication 的主应用程序类不在同一(或更高)包中。如果不想移动Controller,可以新建一个配置类,注解为@ComponentScan

@Configuration
@ComponentScan(basePackages = "com.your.controller.package")
public class FooConfig {
}

即使您可以手动将此配置添加到您的测试弹簧上下文中:@SpringBootTest(classes = FooConfig.class)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2020-01-08
    • 2011-11-06
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    相关资源
    最近更新 更多