使用 Spring Boot 2.0 测试自动配置

工程 | Madhura Bhave | 2018年3月7日 | ...

自动配置是 Spring Boot 最强大的功能之一。自动配置类的测试通常遵循相同的模式。大多数测试启动一个 ApplicationContext,其中包含被测的自动配置类,并且根据测试的不同,还会加载额外的配置来模拟用户行为。这种模式的重复可能会在代码库中增加大量的重复代码。

Spring Boot 2.0 提供了一套新的测试助手,用于轻松配置 ApplicationContext 以模拟自动配置测试场景。 以下示例配置了一个 ApplicationContextRunner 来测试 UserServiceAutoConfiguration

private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
    .withConfiguration(AutoConfigurations.of(UserServiceAutoConfiguration.class));

由于测试类中的大多数测试都共享类似的配置,因此最好将 ApplicationContextRunner 用作测试类的一个字段,并使用一些常用配置进行设置。

每个测试都可以使用所需的配置和属性进一步自定义 ApplicationContext

@Test
public void someTest() {
    this.contextRunner
        .withPropertyValues("user.my.property=test")
	    .withUserConfiguration(MyConfiguration.class)
	    .run(...);
}

除了调用 UserServiceAutoConfiguration 之外,上面的示例还注册了 MyConfiguration 并将 user.my.property 属性设置为 test

ApplicationContextRunner 透明地复制 Spring Boot 使用的配置初始化顺序(首先扫描用户配置,然后按照定义的顺序自动配置)。

支持 AssertableApplicationContext,它在 ApplicationContext 上提供 AssertJ 风格的断言。 您还可以链接多个断言,如以下示例所示

@Test
public void someTest() {
    this.contextRunner.run((context) -> {
        assertThat(context).hasSingleBean(MyBean.class);
        assertThat(context).getBeanNames(UserRule.class).hasSize(2);
    });
}

断言也可以用于未能启动的 ApplicationContext,以检查失败的原因。 无论如何,上下文的生命周期不再需要由测试来管理,即上下文会自动关闭。

对于需要 WebApplicationContext 的测试,可以使用 WebApplicationContextRunnerReactiveWebApplicationContextRunner

自动配置也可能受到类路径上是否存在特定 Class 的影响,这可以通过使用 @ConditionalOnClass 注解来实现。 ApplicationContextRunner 可让您测试在运行时给定 Class 不存在时会发生什么。 Spring Boot 附带一个 FilteredClassLoader,运行器可以轻松使用它。 在以下示例中,我们断言如果 UserService 不存在,则自动配置已正确禁用

@Test
public void serviceIsIgnoredIfLibraryIsNotPresent() {
    this.contextRunner
        .withClassLoader(new FilteredClassLoader(UserService.class))
        .run((context) -> assertThat(context)
                .doesNotHaveBean("userService"));
}

获取 Spring 新闻通讯

通过 Spring 新闻通讯保持联系

订阅

抢占先机

VMware 提供培训和认证,以加速您的进步。

了解更多

获得支持

Tanzu Spring 在一个简单的订阅中提供对 OpenJDK™、Spring 和 Apache Tomcat® 的支持和二进制文件。

了解更多

即将举行的活动

查看 Spring 社区中所有即将举行的活动。

查看全部