简体   繁体   中英

Exclude some beans in test

I have this config in my app ( EngineConfig.java ):

@Component
@EnableAutoConfiguration
@EnableCaching
@EnableScheduling
@ComponentScan(basePackages = "com.exaple.package")
public class EngineConfig {

}

In package I have package components , which contains some beans mark annotation @Component :

在此处输入图片说明

So, I have some test:

@ContextConfiguration(classes = [
    EngineConfig::class
])
@RunWith(SpringRunner::class)
class EngineTest {

    @Test
    fun factorial() {
        //some test
    }
}

The problem is that some beans from the components folder require a Datasource, but in this test I do not need to work with the database, so the Datasource is not created. Is it possible to specify in the test that Spring does not create some beans for which the autowired candidate is not found? Because of this, I get an error like this:

Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]

But in this test I don't need to work with the base, so I would like to exclude the creation of some beans.

You should use Spring profiles. Define your datasource as a bean in your configuration file :

@Configuration
public class EngineConfig {
    @Bean
    @Profile("!test")
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        // define it here
        return dataSource;
    }
}

Then in you test use this annotation to use test profile :

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
class EngineTest {

}

This way it will not define the datasource bean.

Try this in your Test class

@ContextConfiguration(classes = [
EngineConfig::class
])
@RunWith(SpringRunner::class)
**@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, 
DataSourceTransactionManagerAutoConfiguration.class, 
HibernateJpaAutoConfiguration.class})**
class EngineTest {

@Test
fun factorial() {
    //some test
}
}

or you can add this property in application-test.properties as well

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM