我已经创建了一个简单的单元测试,但是IntelliJ错误地将它突出显示为红色。将其标记为错误

没有豆子?

如你所见,它通过了测试?所以它一定是自动连接的?


当前回答

看起来您试图在没有实际激活WebEnvironment的情况下运行测试。

解决方案非常简单,只需添加带有必需配置的@SpringBootTest注释。

这里有一个例子:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) // Run the server for testing.
public class mockTest {

    @Autowired
    // Should work now
}

其他回答

最后一个重要的信息——添加ComponentScan,这样应用程序就知道它需要连接的东西。这与这个问题无关。但是,如果根本没有执行@autowiring,那么这可能是您的解决方案。

@Configuration
@ComponentScan(basePackages = {
    "some_package",
})
public class someService {

我有同样的问题,并解决了它使用“Invalidate Caches…”在文件菜单下。

我总是用以下方法来解决这个问题。 设置>检查>弹簧核心>代码,然后从错误切换到警告的严重性选项

我通过在IDEA中安装mybatis插件解决了这个问题。当我安装Mybatis插件时,它消失了。

I had similar issue in Spring Boot application. The application utilizes Feign (HTTP client synthetizing requests from annotated interfaces). Having interface SomeClient annotated with @FeignClient, Feign generates runtime proxy class implementing this interface. When some Spring component tries to autowire bean of type SomeClient, Idea complains no bean of type SomeClient found since no real class actually exists in project and Idea is not taught to understand @FeignClient annotation in any way.

解决方案:用@Component注解接口SomeClient。(在我们的例子中,我们没有直接在SomeClient上使用@FeignClient注释,而是使用metaannotation @OurProjectFeignClient,它是带注释的@FeignClient,并向其添加@Component注释也可以工作。)