@DataJpaTest 如何指定要扫描的存储库和实体
@DataJpaTest how to specify repositories and entities to scan
默认情况下 @DataJpaTest
扫描所有 jpa 存储库和 @Entity
。在我的例子中,我有 5 个存储库包和 5 个实体包。例如
com.acme.product.entity
与关联
com.acme.product.repository
com.acme.users.entity
与关联
com.acme.users.repository
com.acme.client.entity
与关联
com.acme.client.repository
等等....
我想在单独的课程中测试每个部分。例如
@RunWith(SpringRunner.class)
@DataJpaTest
//Some configurations to import only product repositories and product entities
public class TestProductRepository {
@Autowired
TestEntityManager entityManager;
}
请注意,我已经配置了 5 个不同的 EntityManager
我想导入它们并使用例如 TestProductRepository
中的 productEntityManager
而不是默认的 TestEntityManager
加载全部 repositories/entites。
非常感谢
这就是我如何设法实现我想要的:
@ActiveProfiles( "dev" )
@RunWith( SpringRunner.class )
@DataJpaTest
// Exclude the default test database + the default EntityManager in purpose to use my configurations instead.
@AutoConfigureTestDatabase( connection = H2, replace = AutoConfigureTestDatabase.Replace.AUTO_CONFIGURED )
@Import( {
ProductDataBaseConfig.class,//Import ProductEntityManager and other beans related to DB operations like TransactionManager, etc...
ProductRepositoryContainer.class //Custom bean containing all product repositories
} )
public class TestProductRepository {
@Autowired
private TestEntityManager entityManager;
}
这里重要的是 @AutoConfigureTestDatabase(...)
和 @Import(...)
,因为我替换了自动配置的 bean 并导入了我自己的 ProductEntityManager
,TestEntityManager
使用了提供的配置。
这也减少了 @DataJpaTest
的范围,它不扫描类路径中的所有实体和存储库,这正是我想要的。
默认情况下 @DataJpaTest
扫描所有 jpa 存储库和 @Entity
。在我的例子中,我有 5 个存储库包和 5 个实体包。例如
com.acme.product.entity
与关联
com.acme.product.repository
com.acme.users.entity
与关联
com.acme.users.repository
com.acme.client.entity
与关联
com.acme.client.repository
等等....
我想在单独的课程中测试每个部分。例如
@RunWith(SpringRunner.class)
@DataJpaTest
//Some configurations to import only product repositories and product entities
public class TestProductRepository {
@Autowired
TestEntityManager entityManager;
}
请注意,我已经配置了 5 个不同的 EntityManager
我想导入它们并使用例如 TestProductRepository
中的 productEntityManager
而不是默认的 TestEntityManager
加载全部 repositories/entites。
非常感谢
这就是我如何设法实现我想要的:
@ActiveProfiles( "dev" )
@RunWith( SpringRunner.class )
@DataJpaTest
// Exclude the default test database + the default EntityManager in purpose to use my configurations instead.
@AutoConfigureTestDatabase( connection = H2, replace = AutoConfigureTestDatabase.Replace.AUTO_CONFIGURED )
@Import( {
ProductDataBaseConfig.class,//Import ProductEntityManager and other beans related to DB operations like TransactionManager, etc...
ProductRepositoryContainer.class //Custom bean containing all product repositories
} )
public class TestProductRepository {
@Autowired
private TestEntityManager entityManager;
}
这里重要的是 @AutoConfigureTestDatabase(...)
和 @Import(...)
,因为我替换了自动配置的 bean 并导入了我自己的 ProductEntityManager
,TestEntityManager
使用了提供的配置。
这也减少了 @DataJpaTest
的范围,它不扫描类路径中的所有实体和存储库,这正是我想要的。