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

没有豆子?

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


当前回答

在bean配置文件中放置@Component或@configuration似乎可以工作,例如:

@Configuration
public class MyApplicationContext {
    @Bean
    public DirectoryScanner scanner() {
        return new WatchServiceDirectoryScanner("/tmp/myDir");
    }
}

@Component
public class MyApplicationContext {
    @Bean
    public DirectoryScanner scanner() {
        return new WatchServiceDirectoryScanner("/tmp/myDir");
    }
}

其他回答

我有这个问题。只使用

@SpringBootTest

@AutoConfigureMockMvc

带有测试类的注释。

我使用这个注释来隐藏这个错误,当它出现在IntelliJ v.14:

@SuppressWarnings("SpringJavaAutowiringInspection")

这是另一种“不能自动装配”。No Beans of…”可以通过安装插件来解决,在我的案例中是Spring Batch中的JobBuilderFactory。

我删除了这段代码。不再有错误


另一种检查方法: 将@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
}