Java Spring 如何模拟实现相同接口的bean

Java Spring How to mock beans which implements the same interface

我有一个创建如下的 bean

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

在测试 class 中,我模拟 class 如下:

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

现在。我必须创建第二封电子邮件 class,必须在配置文件“测试”时专门使用。所以我创建了一个接口 (CustomerEmailSender),classes 都实现了它。创建 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 总是被实例化,真正的代码被执行。 即使在测试 class 中从接口更改为 Class-name 也无济于事:

@MockBean
private CustomerEmailSenderImpl2 customerEmailSenderImpl2;

模拟 CustomerEmailSenderImpl2 bean 需要什么?

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

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



@MockBean
private CustomerEmailSender customerEmailSenderImpl2;