2020年7月10日
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
类中指定的设置来运行。