Quarkus 现在支持测试配置文件

随着Quarkus 1.6的发布,Quarkus现已支持测试配置文件,让您可以在同一个模块中轻松测试多种不同的配置。本文概述了什么是测试配置文件以及如何使用它们。

回顾@QuarkusTest如何工作

在讨论测试配置文件之前,让我们简要谈谈@QuarkusTest注解的测试是如何工作的。当这些测试之一首次运行时,Quarkus测试扩展将启动Quarkus。然后Quarkus将保持运行状态,直到测试运行结束。这使得测试非常快速,因为Quarkus只启动一次。然而,它限制您每个模块只能测试一种配置,因为您不能在不同的配置下重新启动Quarkus。测试配置文件打破了这一限制。

测试配置文件

测试配置文件由io.quarkus.test.junit.QuarkusTestProfile接口定义。要定义一个配置文件,您需要提供该接口的一个实现。该接口如下所示:

/**
 * Defines a 'test profile'. Tests run under a test profile
 * will have different configuration options to other tests.
 *
 */
public interface QuarkusTestProfile {

    /**
     * Returns additional config to be applied to the test. This
     * will override any existing config (including in application.properties),
     * however existing config will be merged with this (i.e. application.properties
     * config will still take effect, unless a specific config key has been overridden).
     */
    default Map<String, String> getConfigOverrides() {
        return Collections.emptyMap();
    }

    /**
     * Returns enabled alternatives.
     *
     * This has the same effect as setting the 'quarkus.arc.selected-alternatives' config key,
     * however it may be more convenient.
     */
    default Set<Class<?>> getEnabledAlternatives() {
        return Collections.emptySet();
    }

    /**
     * Allows the default config profile to be overridden. This basically just sets the quarkus.test.profile system
     * property before the test is run.
     *
     */
    default String getConfigProfile() {
        return null;
    }
}

基本上,这个接口允许您执行三项不同的操作:

  • 提供配置覆盖,以便使用不同的配置运行Quarkus。请注意,这些是覆盖项,因此现有配置仍然存在,除非它们已被显式覆盖。

  • 指定一些您希望为该配置文件启用的CDI @Alternatve bean。这允许您将应用程序中的bean替换为测试特定的bean,从而有效地模拟它们。

  • 使用与默认test配置文件不同的配置配置文件运行。

要实际使用此配置文件,我们使用@TestProfile注解来指定它,如下所示:

@QuarkusTest
@TestProfile(MyProfile.class)
public class MyTestClass {
...
}

这个测试类现在将使用MyProfile类中指定的设置来运行。

工作原理

在执行@QuarkusTest之前,Quarkus测试扩展将检查测试想要使用的配置文件,并将其与上次测试使用的配置文件进行比较。如果它们相同,则不采取任何操作,当前正在运行的Quarkus应用程序已在使用正确的配置文件。如果它们不同,则Quarkus将停止,然后以新的配置启动。

一般来说,为了获得最快的测试运行速度,最好尽可能少地停止和启动Quarkus。为此,建议您按字母顺序运行测试,并将所有需要特定配置文件的测试配置到它们自己的包中。这意味着具有相同配置文件的所有测试将一起运行,因此Quarkus将以最少的次数重新启动。

继续前进……

随着时间的推移,这些配置文件将添加更多功能(1.7将包括对每个配置文件的自定义测试资源的支持)。如果您希望支持任何其他功能或有任何其他反馈,请告诉我们。