【问题标题】:@DataJpaTest how to specify repositories and entities to scan@DataJpaTest 如何指定要扫描的存储库和实体
【发布时间】:2019-02-14 22:48:02
【问题描述】:

默认情况下@DataJpaTest 扫描所有 jpa 存储库和@Entity。就我而言,我有 5 个存储库包和 5 个实体包。例如

com.acme.product.entitycom.acme.product.repository com.acme.users.entitycom.acme.users.repository com.acme.client.entitycom.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

非常感谢

【问题讨论】:

  • 如果您有存储库,为什么还需要 EntityManager?
  • @SimonMartinelli 覆盖默认值:TestEntityManager。我只需要一种方法来告诉TestEntityManager 使用这些存储库和实体。
  • 但是如果你想测试 ProductRepository 你可以注入它并且不需要 entitymanager 因为这是配置的
  • @SimonMartinelli 你是对的,但问题是它会减慢测试速度,因为它会扫描所有存储库和所有实体。
  • 我终于找到了一种方法,可以在同一波中覆盖默认的TestEntityManager,每个@DataJpaTest案例的测试时间除以4。

标签: spring-boot spring-data-jpa spring-data spring-boot-test


【解决方案1】:

这就是我设法实现我想要的方式:

@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 的范围,它不会扫描类路径中的所有实体和存储库,这正是我想要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-10
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多