简体   繁体   English

排除测试中的某些豆

[英]Exclude some beans in test

I have this config in my app ( EngineConfig.java ): 我的应用程序( 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 : 在包中,我有包components ,其中包含一些Bean标记注释@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. 问题在于,components文件夹中的某些bean需要数据源,但是在此测试中,我不需要使用数据库,因此不会创建数据源。 Is it possible to specify in the test that Spring does not create some beans for which the autowired candidate is not found? 是否可以在测试中指定Spring不创建某些未找到自动装配候选对象的bean? 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. 但是在此测试中,我不需要使用基础,因此我想排除一些bean的创建。

You should use Spring profiles. 您应该使用Spring配置文件。 Define your datasource as a bean in your configuration file : 在配置文件中将数据源定义为Bean:

@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. 这样,它将不会定义数据源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 或者您也可以在application-test.properties中添加此属性

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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