【问题标题】:How to test a configuration class in Spring Boot如何在 Spring Boot 中测试配置类
【发布时间】:2021-05-22 07:45:19
【问题描述】:

我有以下 Spring Boot 配置类,以便在我们的 MongoDB 中创建索引:

@Configuration
@DependsOn("mongoTemplate")
@Profile({ "!test" })
public class CollectionsConfig {

    private final MongoTemplate mongoTemplate;

    @Autowired
    CollectionsConfig(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @PostConstruct
    public void initIndexes() {
        mongoTemplate.indexOps("db-name"); // collection name string or .class
            .ensureIndex(
                new Index().on("fechaAlta", Sort.Direction.ASC).expire(15552000)
        );
    }
}

既然这个类没有创建任何 bean 或类似的东西,我该如何测试呢?我已经看到了配置类的示例,它们使用应用程序上下文来测试是否创建了 bean,但我没有在这里创建任何 bean,所以我不知道如何运行此代码。

请帮忙。

【问题讨论】:

标签: spring spring-boot spring-mvc junit mockito


【解决方案1】:

我假设测试此配置的一种有意义的方法是验证 @PostConstruct-annotated 方法的副作用。

例如,您可以让@SpringBootTest 加载此配置,然后让您的测试验证在您的嵌入式 Mongo DB 版本上,fechaAlta 上的索引已成功创建。

alternative 将编写一个测试,您手动实例化 CollectionsConfig,向其传递一个模拟的 MongoTemplate 实例,手动调用 @PostConstruct-annotated 方法并最终验证与MongoTemplate 的预期交互是否满足。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-03
    • 2018-11-02
    • 2021-02-16
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 2020-08-08
    • 2017-02-05
    相关资源
    最近更新 更多