6

By default @DataJpaTest scans all jpa repositories and @Entity. In my case I have 5 repositories package and 5 entities package. E.g

com.acme.product.entity is associated with com.acme.product.repository com.acme.users.entity is associated with com.acme.users.repository com.acme.client.entity is associated with com.acme.client.repository

And so on....

I would like to test each part in a separate classe. E.g.

@RunWith(SpringRunner.class)
@DataJpaTest
//Some configurations to import only product repositories and product entities
public class TestProductRepository {
  @Autowired
  TestEntityManager entityManager;
}

Note that I have configured 5 different EntityManager I would like to import them and use for example the productEntityManager in the TestProductRepository instead of the default TestEntityManager which loads all repositories/entites.

Thanks a lot

akuma8
  • 4,160
  • 5
  • 46
  • 82

1 Answers1

1

This is how I manage to achieve what I wanted:

@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; 

}

The important thing here is the @AutoConfigureTestDatabase(...) and @Import(...), as I replaced the autoconfigured beans and import my own ProductEntityManager the TestEntityManager uses that provided configuration. This also reduce the scope of @DataJpaTest which does not scan all entities and repositories in the classpath and that was what I wanted.

akuma8
  • 4,160
  • 5
  • 46
  • 82