【问题标题】:Testing Spring Boot Library Modules测试 Spring Boot 库模块
【发布时间】:2020-01-30 04:41:30
【问题描述】:

我有一个多模块项目,其中并非每个模块实际上都是应用程序,但其中很多是库。这些库正在做主要工作,我想在实现它们的地方测试它们。库的当前依赖项:

implementation 'org.springframework.boot:spring-boot-starter'
testImplementation 'org.springframework.boot:spring-boot-starter-test'

主要来源是一个带有 @Configuration 和单个 bean 的类:

@Bean public String testString() { return "A Test String"; }

我有 2 个测试课程:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles({"default", "test"}) 
public class Test1 {  

    @Test
    public void conextLoaded() {
    }
}

-

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles({"default", "test"}) 
public class Test2 {  
    @Autowired
    private String testString; 

    @Test
    public void conextLoaded() {
    }
}

第一个测试有效。第二个没有。该项目中的任何地方都没有@SpringBootApplication,因此在与测试相同的包中我添加了一个测试配置:

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.to.config") 
public class LibTestConfiguration {
}

而且它不起作用。 @Service 的类也是如此。它们不在上下文中。我怎样才能让它像一个普通的 Spring 启动应用程序一样运行,而不需要它真正成为一个并从我需要的配置文件中加载配置和上下文?默认配置文件和测试配置文件共享它们的大部分属性(目前),我希望像启动 tomcat 一样加载它们。

【问题讨论】:

  • 理想情况下,您的库组件应该是可单元测试的。
  • 这是计划,但它们仍将是具有特定测试配置的服务和组件。另一种方法是我自己初始化服务,但这对我来说听起来不对。
  • 您熟悉测试模拟吗?通常,您一次测试一个服务,在执行过程中模拟它们的每个依赖项。
  • 是的,但是例如,如果依赖项是数据库并且我有一个复杂的查询要测试,该怎么办?我也想测试弹簧数据存储库。它们通常是由 Spring Boot 在运行时创建的。我在那里也有一个弹性搜索索引。这些查询往往会很快变得复杂,而且往往会在这里和那里中断。我了解隔离部分,对于大多数服务,你是对的,我可以在测试运行时自己注入依赖项(主要是字符串配置)。但是对于 spring 提供的那些实现,我不知道如何(仍然更喜欢外部 testconf)

标签: java spring spring-boot unit-testing automated-tests


【解决方案1】:

我切换到 JUnit 5 并让它有点工作......所以如果你想测试数据库的东西:

@DataMongoTest
@ExtendWith(SpringExtension.class)
@ActiveProfiles({"default", "test"})
class BasicMongoTest { ... }
  • 让您自动装配所有存储库和 mongo 模板
  • 使用 apllicaton.yml 配置初始化
  • 不初始化或配置拦截器

如果您的类路径中有一个带有 @SpringBootApplication 的类,则完整的应用程序上下文测试(在您的测试上下文中可以是一个空的测试主目录)

@SpringBootTest
@ExtendWith(SpringExtension.class)
@ActiveProfiles({"default", "test"})
public class FullContextTest { ... }
  • 使用所有配置和 bean 初始化完整上下文
  • 如果没有必要,则不应这样做,因为它会加载所有应用程序上下文,并且有点违背单元测试的目的,即仅激活所需的内容。

仅测试特定组件和配置:

@SpringBootTest(classes = {Config1.class, Component1.class})
@EnableConfigurationProperties
@ExtendWith(SpringExtension.class)
@ActiveProfiles({"default", "test"})
public class SpecificComponentsTest { ... }
  • 仅使用 Config1 和 Component1 类初始化上下文。 Component1 和 Config1 中的所有 bean 都可以自动装配。

【讨论】:

  • 请注意,@ExtendWith(SpringExtension.class) 在使用 @SpringBootTest 时是多余的
猜你喜欢
  • 2020-09-24
  • 1970-01-01
  • 2018-04-15
  • 2015-03-23
  • 2021-08-01
  • 2017-02-09
  • 1970-01-01
  • 2016-10-03
  • 2020-10-02
相关资源
最近更新 更多