【问题标题】:Java Spring How to mock beans which implements the same interfaceJava Spring如何模拟实现相同接口的bean
【发布时间】:2021-09-03 03:22:38
【问题描述】:

我有一个如下创建的 bean

@Profile({"test", "dev", "int"})
@Bean
public CustomerEmailSenderImpl customerEmailSenderImpl(){
    return new CustomerEmailSenderImpl ();
}

在一个测试类中,我将这个类模拟如下:

   @ActiveProfiles(profiles = {"test"})
   .....
    @MockBean
    private CustomerEmailSenderImpl customerEmailSenderImpl;

现在。我必须创建第二个电子邮件类,必须在配置文件“测试”时专门使用它。所以我创建了两个类都实现的接口(CustomerEmailSender)。 bean的创建过程如下。

@Profile({"dev", "int"})
@Bean(name = "customerEmailSender")
public CustomerEmailSender customerEmailSenderImpl1(){
    return new CustomerEmailSenderImpl1 ();
}

@Profile({"test"})
@Bean(name = "customerEmailSender")
public CustomerEmailSender customerEmailSenderImpl2(){
    return new CustomerEmailSenderImpl2 ();
}

Mock 我改了关注

@ActiveProfiles(profiles = {"test"})
...
@MockBean
private CustomerEmailSender customerEmailSender;

应用程序启动时没有错误。 但是测试并没有模拟 bean CustomerEmailSenderImpl2。 bean 总是被实例化,并且真正的代码被执行。 即使在测试类中从 Interface 更改为 Class-name 也无济于事:

@MockBean
private CustomerEmailSenderImpl2 customerEmailSenderImpl2;

要模拟 bean CustomerEmailSenderImpl2 需要什么?

【问题讨论】:

  • 这完全是为了嘲笑课堂。否则一切正常。
  • 在这种情况下,您的标题与您的问题无关。你知道如何使用模拟框架吗?我个人主要使用 Mockito
  • 如果您在配置中使用return new CustomerEmailSenderImpl2 (),我看不出您希望如何返回模拟。
  • 我更新了标题,更好地总结了这个问题

标签: java spring-boot mockito spring-test


【解决方案1】:

解决方法是使用@Qualifier,然后在测试类中使用限定符名称作为变量名。

@Profile({"test"})
@Bean(name = "customerEmailSender")
@Qualifier(value="customerEmailSenderImpl2")
public CustomerEmailSender customerEmailSenderImpl2(){
    return new CustomerEmailSenderImpl2 ();
}



@MockBean
private CustomerEmailSender customerEmailSenderImpl2;

【讨论】:

    猜你喜欢
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多