spring boot 测试错误的配置类

标签 spring spring-boot testing junit apache-kafka

我正在尝试使用 Spring Boot 2.0.1 测试我的存储库层,但是当我运行我的测试类时,Spring 尝试实例化一个不是来自测试包的配置类。

测试代码如下:

测试配置类

@Configuration
@Import(value = {TestDatabaseConfig.class})
@Profile("local")
public class TestConfig {

}

TestDatabaseConfig.class

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "logEntityManagerFactory",
        transactionManagerRef = "logTransactionManager",
        basePackages = { "it.xxx.yyy.repository.log" })
@EntityScan(basePackages = {"it.xxx.yyy.model.log", "it.xxx.yyy.common"})
@Profile("local")
public class TestDatabaseConfig {

@Bean("logDataSourceProperties")
public DataSourceProperties logDataSourceProperties() {
    return new DataSourceProperties();
}


@Bean(name = "logDataSource")
public DataSource dataSource(@Qualifier("logDataSourceProperties") DataSourceProperties properties) {
    return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.H2)
            .addScript("classpath:schema.sql")
            .build();
}

@Bean(name = "logEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean logEntityManagerFactory(EntityManagerFactoryBuilder builder,
                                                                      @Qualifier("logDataSource") DataSource logDataSource) {
    return builder.dataSource(logDataSource)
            .packages("it.xxx.model.log")
            .persistenceUnit("log")
            .build();
}

@Bean(name = "logTransactionManager")
public PlatformTransactionManager logTransactionManager(@Qualifier("logEntityManagerFactory")EntityManagerFactory logEntityManagerFactory) {
    return new JpaTransactionManager(logEntityManagerFactory);
}

当我运行这个类时

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("local")
public class LogRepositoryTest {

    @Autowired
    private ResultLogRepository resultLogRepository;

    @Test
    public void init(){
    }
}

它说:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'kafkaProducer': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'kafka.topic.operation' in value "${kafka.topic.operation}"
[...]
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'kafka.topic.operation' in value "${kafka.topic.operation}"

但我不明白为什么它会从我的主包(上面有 @Configuration 注释)中调出我的 KafkaProducer.class。

最佳答案

在您的 LogRepositoryTest 测试类中,您应该指出应该考虑的备用测试配置类,在您的情况下我认为应该是 TestConfig

来自 Spring Boot documentation :

If you are familiar with the Spring Test Framework, you may be used to using @ContextConfiguration(classes=…​) in order to specify which Spring @Configuration to load. Alternatively, you might have often used nested @Configuration classes within your test.

所以用@ContextConfiguration(classes = {TestConfig.class})注释LogRepositoryTest

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("local")
@ContextConfiguration(classes = {TestConfig.class})
public class LogRepositoryTest {

    @Autowired
    private ResultLogRepository resultLogRepository;

    @Test
    public void init(){
    }
}

更新

同时注释您的配置类:

@EnableAutoConfiguration

类似于:

@Configuration
@EnableAutoConfiguration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "logEntityManagerFactory",
        transactionManagerRef = "logTransactionManager",
        basePackages = { "it.xxx.yyy.repository.log" })
@EntityScan(basePackages = {"it.xxx.yyy.model.log", "it.xxx.yyy.common"})
@Profile("local")
public class TestDatabaseConfig {
//...
}

更新 2

对于错误:

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.autoconfigure.jdbc.DataSourceProperties' available: expected single matching bean but found 2: logDataSourceProperties,spring.datasource-org.springframework.boot.autoconfigure.jdbc.DataSourceProperties

完全删除方法:

@Bean("logDataSourceProperties")
public DataSourceProperties logDataSourceProperties() {
    return new DataSourceProperties();
}

并改变你的:

@Bean(name = "logDataSource")
public DataSource dataSource(@Qualifier("logDataSourceProperties") DataSourceProperties properties) {
 // ...
}

到:

@Bean(name = "logDataSource")
public DataSource dataSource(DataSourceProperties properties) {
 // ...
}

关于spring boot 测试错误的配置类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51017799/

相关文章:

java - 获取 java.lang.IllegalArgumentException : argument type mismatch error on using "RedirectAttributes" in spring MVC

spring - 在 wildfly 10 中将 http 请求重定向到 https

spring-boot - Spring Cloud Eureka 服务器示例登录挑战

java - HttpClientErrorException : 404 null

testing - 检查网络应用程序爬虫是否有任何错误?

testing - 在验收测试中检查数据库的状态是一种好习惯吗?

testing - 在 Spock 中,如何消除 "then" block 中的重复交互?

java - 如何在 H2 中设置 sysdate? (供测试用)

java - 在 Spring Boot 的 application.properties 中使用系统变量

json - 获取 HTTP 状态 400 - 客户端发送的请求在语法上不正确 : using curl to post/put json request