【问题标题】:Spring boot test - No qualifying bean of type 'com.example.MyService' availableSpring Boot 测试 - 没有可用的“com.example.MyService”类型的合格 bean
【发布时间】:2018-11-08 14:50:31
【问题描述】:

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

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

代码如下:

测试类:

@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 可以为 null 用于测试目的。

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

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

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

@TestConfiguration
static class MyServic1TestContextConfiguration {

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

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

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

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

【问题讨论】:

  • 尝试返回 new MyService() 而不是 null 只是为了检查错误是否仍然存在。
  • 哈,@NiVeR。错误似乎消失了。现在我面对一堆豆子要那样做。问题:我可以在@Configuration MyIntegrationTestConfig 类中使用@MockBean 吗?我试过了,看起来还可以,但不确定在配置类中这样做是否正确。
  • 所以也许最后一个问题是,为什么 Spring boot 将 null 视为没有 bean?刚刚搜索,没有找到任何相关的文档。
  • 对于最后一个问题,有一个很好的答案:stackoverflow.com/questions/2707322/what-is-null-in-java
  • @Simo 您的问题包含一些不错的代码! +1

标签: java spring spring-boot spring-boot-test


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-07-29
    • 2020-01-31
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2018-04-20
    • 2019-02-04
    • 2019-02-23
    • 1970-01-01
    相关资源
    最近更新 更多