【问题标题】:How to make a custom spring boot starter loadable while integration test?如何在集成测试时使自定义 Spring Boot 启动器可加载?
【发布时间】:2020-04-11 22:18:24
【问题描述】:

我们创建了一个自定义 Spring Boot 启动器,其中包含几个可重用的跨内部项目的通用功能。 启动器按预期工作正常。但是,在集成测试时,使用 starter 的项目无法找到自定义 starter 创建的所有 bean。

注意:内部项目在其集成测试类中使用注释@SpringBootTest 以加载整个弹簧上下文。

【问题讨论】:

  • 如果启动器在运行时工作,它也应该在注释为 @SpringBootTest 的测试中工作。在这两种情况下,都应该通过spring.factories 中的条目找到启动器的自动配置类。您能否提供一个 minimal, complete, and verifiable example 来代表您的自定义启动器并显示在运行时工作但在集成测试中不工作的东西?

标签: java spring-boot spring-boot-starter


【解决方案1】:

感谢您的回答。

正常执行内部项目时,我清楚地看到他们正在获取 bean 实例,而无需添加任何自定义组件扫描。我们刚刚将自定义启动器添加到它们的依赖项中。我不明白为什么在集成测试时没有加载它。 (我认为应该向Spring社区报告)

通过将 CommonAutoConfiguration 类导入内部项目集成类,我找到了一种我认为不是最佳解决方案的解决方法。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { InternalProjectbootApplication.class })
@DataMongoTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class)
@Import(CommonAutoConfiguration.class)
public class ArchiveUnitServiceITTest implements ServiceInterfaceIT {...

【讨论】:

    【解决方案2】:

    如果没有更多信息,我会说您的自定义 spring-boot-starter 没有相同的命名空间,因此不会从您的内部应用程序中扫描组件。

    假设您的内部项目命名空间是:com.hello.package.p1,而您的 Spring-boot-starter 具有命名空间:net.greeting.package.p1

    试试这样的:

    @SpringBootTest(classes = TestConfiguration.class)

    在您的 TestConfiguration.class 中:

    @Configuration
    @ComponentScan(basePackages = "net.greeting.package.p1")
    public static class TestConfiguration {
    
        // ...
    
    }
    

    【讨论】:

    • 感谢您的回答。由于 spring boot starter 旨在减少使用它的项目的配置,您认为在 starter 包周围添加显式组件扫描是最好的解决方案吗?如果是,与简单的 Maven 模块相比有什么好处?
    猜你喜欢
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 2020-02-25
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多