我正在编写一个junit测试,其中我需要自动连接接口的特定实现。我使用@Mock注解来自动连接实现。我正在使用配置文件和一个配置文件来确定哪个实现是Autowire。运行测试类EmailTest时,控制台上会出现以下错误消息:
原因: java.lang.IllegalStateException:无法注册模拟bean ....需要一个要替换的匹配bean,但找到了customerEmailSender、emailSenderImpl_1、emailSenderImpl_2
原因是Spring没有找到或使用配置类: BeanConfiguration。我之所以知道这一点,是因为我在BeanConfiguration类中设置了断点,而应用程序不会中断。
Spring没有发现或使用配置类BeanConfiguration的原因可能是什么。
@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();
}
}发布于 2021-06-11 18:38:29
检查BeanConfiguration包是否在spring的组件扫描边界内
发布于 2021-06-11 18:41:46
问题是@MockBean不知道要替换哪个bean (并且您有多个相同接口的bean)。
试一试
@MockBean(name = "customerEmailSender")
private CustomerEmailSender customerEmailSender;https://stackoverflow.com/questions/67935414
复制相似问题