首页 > 解决方案 > Spring Boot 测试 - 没有可用的“com.example.MyService”类型的合格 bean

问题描述

stackoverflow 上有很多类似的问题,但我发现没有一个是我的情况。

在我与 Spring boot 2.0.2.RELEASE的集成测试中,我为测试创建了一个单独的 @Configuration 类,我在其中定义了 bean com.example.MyService。这个 bean 恰好被com.example.OtherBean.

这是代码:

测试类:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {MyIntegrationTestConfig.class},
        webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public class MyService1Test extends MyAbstractServiceIntegrationTest {
@Test
    public void someTest() {}
}

设置和拆卸的通用摘要:

public class MyAbstractServiceIntegrationTest{
    @Before
    public void setUp(){}

    @After
    public void tearDown()
}

src/test 中的 MyIntegrationTestConfig,用于代替 src/main 中的配置:

@Configuration
@ComponentScan({"com.example"})
public class MyIntegrationTestConfig {
   @Bean
   public MyService myService() {
      return null;
   }
}

MyService出于测试目的,bean 可以为空。

当我运行测试时,我不断收到以下错误:

没有可用的“com.example.MyService”类型的合格 bean:预计至少有 1 个符合自动装配候选资格的 bean。依赖注释:{}

我什至尝试将这个内部类添加到 MyServic1Test。仍然没有帮助:

@TestConfiguration
static class MyServic1TestContextConfiguration {

    @Bean(name = "MyService")
    public MyService myService() {
        return null;
    }
}

知道我在这里做错了什么吗?还是我错过了什么?

我的怀疑是 Spring 会先尝试在 src/main 文件夹中创建/自动装配 bean,然后再创建在 src/test 文件夹中定义的 MyService bean。会是这样吗?或者是否存在 bean MyService 所在的不同上下文(如测试上下文),而其他 bean 存在于其他上下文中并且无法找到 MyService。

一个附带问题:对于集成测试,可以使用 webEnvironment = SpringBootTest.WebEnvironment.MOCK,对吗?

标签: javaspringspring-bootspring-boot-test

解决方案


问题是您如何初始化 bean。该值null是导致问题的值。就好像您实际上没有声明该对象的任何实例。为了使它工作,声明一个有效的服务实例new MyService()


推荐阅读