How do I import configuration classes in a @DataJpaTest in a SpringBootTest?

后端 未结 3 1783
孤城傲影
孤城傲影 2020-12-31 04:54

I have a SpringBoot Application and I a config package with

@Configuration
@EnableJpaAuditing
public class PersistenceConfig {
}


        
相关标签:
3条回答
  • 2020-12-31 05:18

    You can try this: annotate PersistenceConfig with @ComponentScan to enable component scanning in Spring.

    @Configuration
    @EnableJpaAuditing
    @ComponentScan(basePackages = "com.yourbasepackage")
    public class PersistenceConfig {
    }
    

    With no further configuration, @ComponentScan will default to scanning the same package as the PersistenceConfig class.

    And add the @Context-Configuration annotation to tell it to load its configuration from the PersistenceConfig.class.

    @RunWith( SpringRunner.class )
    @DataJpaTest
    @ContextConfiguration(classes=PersistenceConfig.class)
    public class PersonRepositoryTest {
    
        // Tests ...
    }
    
    0 讨论(0)
  • 2020-12-31 05:21

    A solution is to use @Import to import your configuration to the configuration done by @DataJpaTest. This is my understanding of @Import.

    @RunWith(SpringRunner.class)
    @DataJpaTest
    @Import(AuditConfiguration.class)
    public class AuditTest {
    }
    

    with AuditConfiguration that enables auditing

    @Configuration
    @EnableJpaAuditing
    public class AuditConfiguration {
    }
    
    0 讨论(0)
  • 2020-12-31 05:41

    After @georges van post I have found out that ALL configuration classes get also picked up by just adding one line in the test:

    @RunWith( SpringRunner.class )
    @DataJpaTest
    @ComponentScan(basePackages = "com.basepackage.config")
    public class PersonRepositoryTest {
    
        // Tests ...
    }
    

    If someone only wants ONE specific configuration class you can do:

    @RunWith( SpringRunner.class )
    @DataJpaTest
    @ContextConfiguration(classes=MyConfig.class)
    public class PersonRepositoryTest {
    
        // Tests ...
    }
    

    Or multiple classes with:

    @ContextConfiguration(classes={MyConfig1.class, MyConfig2.class})

    0 讨论(0)
提交回复
热议问题