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

没有豆子?

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


当前回答

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

其他回答

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

例如:

@Component
@EnableAutoConfiguration  
public class ItemDataInitializer  {

    @Autowired
    private ItemReactiveRepository itemReactiveRepository;

    @Autowired
    private MongoOperations mongoOperations;
}

我在申请的时候也遇到过类似的问题。 当我添加注释时,不正确的高亮显示消失了。

@ContextConfiguration(classes = {...})

将@Service注释添加到Repository类中,它应该可以工作。

看起来您试图在没有实际激活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 {