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

没有豆子?

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


当前回答

你所需要做的是让这个工作是以下代码:

@ComponentScan
public class PriceWatchTest{

    @Autowired
    private PriceWatchJpaRepository priceWatchJpaRepository;
...
...
}

其他回答

我有这个问题。只使用

@SpringBootTest

@AutoConfigureMockMvc

带有测试类的注释。

在使用@SpringBootApplication注释创建SpringBoot应用程序时,我也遇到了同样的问题。该注释根据spring引用表示@Configuration、@EnableAutoConfiguration和@ComponentScan。

正如预期的那样,新的注释工作正常,我的应用程序运行顺利,但Intellij一直抱怨未实现的@Autowire依赖项。当我重新分别使用@Configuration、@EnableAutoConfiguration和@ComponentScan时,错误就停止了。Intellij 14.0.3(很可能是更早的版本)似乎还没有配置为识别@SpringBootApplication注释。

现在,如果错误对您的影响如此之大,那么就恢复到那三个单独的注释。否则,忽略Intellij…您的依赖项解析配置正确,因为您的测试通过了。

永远记得……

人永远比机器伟大。

在类级别使用@EnableAutoConfiguration注释和@Component。它将解决这个问题。

例如:

@Component
@EnableAutoConfiguration  
public class ItemDataInitializer  {

    @Autowired
    private ItemReactiveRepository itemReactiveRepository;

    @Autowired
    private MongoOperations mongoOperations;
}

有时需要指明@ComponentScan应该在哪里扫描组件。你可以通过将包作为这个注释的参数来实现,例如:

@ComponentScan(basePackages={"path.to.my.components","path.to.my.othercomponents"})

然而,正如前面提到的,@SpringBootApplication注释替换了@ComponentScan,因此在这种情况下,你必须做同样的事情:

@SpringBootApplication(scanBasePackages={"path.to.my.components","path.to.my.othercomponents"})

至少在我的案例中,Intellij停止了抱怨。

我只能使用@EnableAutoConfiguration来解决它,但是这个错误没有功能上的影响。