定义 2 个数据源时模拟 EntityManagerFactory

Mocking EntityManagerFactory when 2 Datasources are defined

所以,我的应用程序连接到 2 个 Mysql 数据库。 由于我添加了对 2 个数据库的支持,我的 Mockito 测试以这个异常结束:

Caused by: java.lang.IllegalStateException: Unable to register mock bean javax.persistence.EntityManagerFactory expected a single matching bean to replace but found [myCustomEntityManager1, myCustomerEntityManager2]

这是目前的声明方式

@MockBean
private EntityManagerFactory entityManagerFactory;

这就是我声明自定义 entityManager 的方式:

@Bean
public LocalContainerEntityManagerFactoryBean myCustomEntityManager1() {
    return entityManagerConfiguration.getEntityManager(MY_PACKAGE, getDatasource());
}

@MockBean 采用 name 属性,允许您指定要注册或替换的 bean 的名称。

你的情况:

@MockBean(name="myCustomEntityManager1")
private EntityManagerFactory entityManagerFactory;

您可能还想 give your bean a more descriptive name

While a name() attribute is available, the default strategy for determining the name of a bean is to use the name of the @Bean method. This is convenient and intuitive, but if explicit naming is desired, the name attribute (or its alias value) may be used. Also note that name accepts an array of Strings, allowing for multiple names (i.e. a primary bean name plus one or more aliases) for a single bean.