我正在编写一个junit测试,其中我需要自动连接接口的特定实现。我正在使用@Mock注释来自动连接实现。我正在使用配置文件和配置文件来确定Autowire的实现。运行测试类EmailTest时,控制台上会出现以下错误消息:
由以下原因引起:java.lang.IllegalStateException:无法注册mock bean。。。。需要替换单个匹配的bean,但找到[customerEmailSender,emailSenderImpl_1,emailSenderImpl_2]
原因是Spring没有找到或使用配置类:BeanConfiguration。我知道这一点是因为我在类BeanConfiguration中放置了一个断点,应用程序不会中断。
Spring没有找到或使用配置类BeanConfiguration的raeson可能是什么。
@RunWith(SpringRunner.class)
@ActiveProfiles(profiles = {"test-unit"})
@Import(BeanConfiguration.class)
public class EmailTest {
@MockBean
private CustomerEmailSender customerEmailSender;
}
@Configuration
public class BeanConfiguration {
@Profile({"test-unit"})
@Bean(name = "customerEmailSender")
public CustomerEmailSender emailSenderImpl_1(){
return new EmailSenderImpl_1();
}
@Profile({"prd"})
@Bean(name = "customerEmailSender")
public CustomerEmailSender emailSenderImpl_2(){
return new EmailSenderImpl_2();
}
}
检查BeanConfiguration包是否位于spring的组件扫描边界中
问题是@MockBean
不知道要替换哪个bean(并且您有多个相同接口的bean(。
尝试
@MockBean(name = "customerEmailSender")
private CustomerEmailSender customerEmailSender;