mercredi 23 janvier 2019

Why is the entity manager not null in the spring boot test parent but it is null in the repository?

I've got the entity manager in the parent test class

@RunWith(SpringRunner.class)
@SpringBootTest(
    properties = {
            "spring.profiles.active=test",
            "spring.config.name=app-test"})
public abstract class ViewerTestBase extends DbBuilderImpl {

@Autowired EntityManager em;

The entity manager here is OK. DbBuilder sets up test data. In the @repository it is null

@Repository public class PaymentTransactionDao {
@Autowired EntityManager em;

Causing the test case to fail.

The entity manager is mapped to the h2 database for tests.

The persistence config class is boiler plate

@Configration
@EnableTransactionManagement
public class PersistenceConfig {

  @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
    LocalContainerEntityManagerFactoryBean em = builder.dataSource(viewerDataSource())
            .packages("viewer.model")
            .persistenceUnit("viewer")
            .build();
    return em;
  }

  @Bean
  public PlatformTransactionManager transactionManager(
        EntityManagerFactory viewerEntityManagerFactory) {
    return new JpaTransactionManager(pspEntityManagerFactory);
  }

  @Bean
  @Primary
  @ConfigurationProperties(prefix = "viewer.dbo.datasource")
  public DataSource viewerDataSource() {
    return DataSourceBuilder.create().build();
  }

  @Bean
  @ConfigurationProperties(prefix = "viewer.auth.datasource")
  public DataSource authDataSource() {
    return DataSourceBuilder.create().build();
  }

Setup with spring boot starter jpa

compile group: 'org.springframework.boot', name: 'spring-boot-starter-web'
compile("org.springframework.boot:spring-boot-devtools")
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa'

testCompile group: 'junit', name: 'junit', version: '4.12'
testCompile group: 'com.h2database', name: 'h2'
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile group: 'org.springframework.boot', name: 'spring-boot-test'
testCompile group: 'org.springframework.boot', name: 'spring-boot-test-autoconfigure'

Aucun commentaire:

Enregistrer un commentaire