Pruebas continuas
Aprenda a utilizar las pruebas continuas en su aplicación Quarkus.
1. Requisitos previos
To complete this guide, you need:
-
Roughly 15 minutes
-
An IDE
-
JDK 17+ installed with
JAVA_HOME
configured appropriately -
Apache Maven 3.9.9
-
Optionally the Quarkus CLI if you want to use it
-
Optionally Mandrel or GraalVM installed and configured appropriately if you want to build a native executable (or Docker if you use a native container build)
-
La aplicación de bienvenida completada de la Guía de Inicio
2. Introducción
Quarkus admite pruebas continuas, donde las pruebas se ejecutan inmediatamente después de guardar los cambios en el código. Esto le permite obtener retroalimentación instantánea sobre sus cambios en el código. Quarkus detecta qué pruebas cubren qué código, y utiliza esta información para ejecutar sólo las pruebas necesarias cuando se cambia el código.
3. Solución
Inicie la aplicación "Getting Started " (o cualquier otra aplicación) utilizando:
quarkus dev
./mvnw quarkus:dev
./gradlew --console=plain quarkusDev
Quarkus se iniciará en modo de desarrollo como es normal, pero en la parte inferior de la pantalla debería ver lo siguiente:
--
Tests paused, press [r] to resume, [h] for more options>
Pulse r
y las pruebas comenzarán a ejecutarse. Usted debe ver el cambio de estado en la parte inferior de la pantalla, ya que se están ejecutando, y debe terminar con:
--
Tests all passed, 2 tests were run, 0 were skipped. Tests took 1470ms.
Press [r] to re-run, [v] to view full results, [p] to pause, [h] for more options>
Si desea que las pruebas continuas se inicien automáticamente, puede configurar quarkus.test.continuous-testing=enabled en application.properties . Si no desea que se inicien en absoluto, puede cambiar este valor a disabled .
|
Ahora puede empezar a hacer cambios en su aplicación. Entre en GreetingResource
y cambie el método hello
para que devuelva "hello world"
, y guarde el archivo. Quarkus debería volver a ejecutar inmediatamente la prueba, y usted debería obtener una salida similar a la siguiente:
2021-05-11 14:21:34,338 ERROR [io.qua.test] (Test runner thread) Test GreetingResourceTest#testHelloEndpoint() failed
: java.lang.AssertionError: 1 expectation failed.
Response body doesn't match expectation.
Expected: is "hello"
Actual: hello world
at io.restassured.internal.ValidatableResponseImpl.body(ValidatableResponseImpl.groovy)
at org.acme.getting.started.GreetingResourceTest.testHelloEndpoint(GreetingResourceTest.java:21)
--
Test run failed, 2 tests were run, 1 failed, 0 were skipped. Tests took 295ms
Press [r] to re-run, [v] to view full results, [p] to pause, [h] for more options>
Vuelva a cambiarlo y las pruebas se ejecutarán de nuevo.
4. Control de las pruebas continuas
Existen varias teclas de acceso rápido que puede utilizar para controlar las pruebas continuas. Si pulsa h
aparecerá la siguiente lista de comandos:
The following commands are available:
[r] - Re-run all tests
[f] - Re-run failed tests
[b] - Toggle 'broken only' mode, where only failing tests are run (disabled)
[v] - Print failures from the last test run
[p] - Pause tests
[o] - Toggle test output (disabled)
[i] - Toggle instrumentation based reload (disabled)
[l] - Toggle live reload (enabled)
[s] - Force restart
[h] - Display this help
[q] - Quit
Se explican a continuación:
- [r] - Volver a ejecutar todas las pruebas
-
Esto volverá a ejecutar todas las pruebas
- [f] - Volver a ejecutar las pruebas fallidas
-
Esto volverá a ejecutar cada prueba que falle
- [b] - Activar el modo "sólo fallidas", en el que sólo se ejecutan las pruebas que fallan
-
El modo de sólo fallidas únicamente ejecutará las pruebas que hayan fallado previamente, incluso si otras pruebas se ven afectadas por un cambio en el código. Esto puede ser útil si está modificando código que es utilizado por muchas pruebas, pero sólo quiere centrarse en depurar la que ha fallado.
- [v] - Imprime los fallos de la última prueba realizada
-
Imprime los fallos en la consola de nuevo, esto puede ser útil si ha habido mucha salida en la consola desde la última ejecución.
- [p] - Pausa de las pruebas
-
Detiene temporalmente la ejecución de las pruebas. Esto puede ser útil si usted está haciendo muchos cambios, y no quiere retroalimentación hasta que estén todos hechos.
- [o] - Conmutar la salida de la prueba
-
Por defecto, la salida de prueba se filtra y no se muestra en la consola, de modo que la salida de prueba y la salida del modo desarrollo no se intercalan. Al habilitar la salida de prueba se imprimirá la salida en la consola cuando se ejecuten las pruebas. Incluso cuando la salida está desactivada, la salida filtrada se guarda y se puede ver en la Dev UI.
- [i] - Activar la recarga basada en la instrumentación
-
Esto no está directamente relacionado con las pruebas, pero le permite activar la recarga basada en la instrumentación. Esto permitirá la recarga en vivo para evitar un reinicio si un cambio no afecta a la estructura de una clase, lo que proporciona una recarga más rápida y le permite mantener el estado.
- [l] - Activar la recarga en vivo
-
Esto no está directamente relacionado con las pruebas, pero le permite activar y desactivar la recarga en vivo.
- [s] - Forzar el reinicio
-
Esto forzará un escaneo de archivos modificados y realizará una recarga en vivo con los cambios. Tenga en cuenta que incluso si no hay cambios la aplicación se reiniciará. Esto seguirá funcionando incluso si la recarga en vivo está desactivada.
5. Pruebas continuas sin modo de desarrollo
It is possible to run continuous testing without starting dev mode. This can be useful if dev mode will interfere with
your tests (e.g. running wiremock on the same port), or if you only want to develop using tests. To start continuous testing
mode, run mvn quarkus:test
or gradle quarkusTest
.
La interfaz de usuario de desarrollo no está disponible cuando se ejecuta en el modo de pruebas continuas, ya que esto es proporcionado por el modo de desarrollo. |
6. Selecting Tests to Run
The configuration properties quarkus.test.include-pattern
and quarkus.test.exclude-pattern
can be used to select which tests to run.
They are regular expressions matched against the fully qualified class name of the test class.
If include-patterns
is configured, exclude-patterns
is ignored.
Alternatively, an approach native to the build system may be used.
In Maven, that is the -Dtest=...
system property, while in Gradle, it is the --tests ...
command line option.
These options, when used with maven quarkus:[dev|test]
or gradle quarkus[Dev|Test]
, work just like they work with mvn test
or gradle test
, except that they filter the set of tests executed during continuous testing.
When these options are used, the quarkus.test.[include|exclude]-pattern
configuration is ignored.
6.1. Maven
The -Dtest=...
system property selects given test(s) for continuous testing.
The format of this configuration property is the same as the Maven Surefire -Dtest=...
format.
Specifically: it is a comma (,
) separated list of globs of class file paths and/or method names.
Each glob can potentially be prefixed with an exclamation mark (!
), which makes it an exclusion filter instead of an inclusion filter.
Exclusions have higher priority than inclusions.
The class file path glob is separated from the method name glob by the hash sign (#
) and multiple method name globs may be present, separated by the plus sign (+
).
For example:
-
Basic*
: all classes starting withBasic
-
???Test
: all classes named with 3 arbitrary characters followed byTest
-
!Unstable*
: all classes except classes starting withUnstable
-
pkg/**/Ci*leTest
: all classes in the packagepkg
and subpackages, starting withCi
and ending withleTest
-
*Test#test*One+testTwo?????
: all classes ending withTest
, and in them, only methods starting withtest
and ending withOne
, or starting withtestTwo
and followed by 5 arbitrary characters -
#fast*+slowTest
: all classes, and in them, only methods starting withfast
or methods namedslowTest
Note that the syntax %regex[...]
and %ant[...]
is NOT supported.
6.2. Gradle
The --tests ...
command line option selects given test(s) for continuous testing.
The format is the same as the gradle test --tests ...
format.
Specifically: the option can be passed multiple times, and each item is a simple pattern for the test class name and optionally a method name.
When the pattern starts with an upper case letter, it matches a simple name of the class; otherwise, it matches a fully qualified name of the class.
After the class name, separated by a period (.
), a method name pattern may be included.
The only wildcard character supported is *
, which matches an arbitrary number of characters.
Note that *
is based purely on text, it doesn’t pay extra attention to package delimiters.
For example:
-
com.example.Basic*
: all classes in packagecom.example
starting withBasic
-
MyTest*
: all classes whose simple name starts withMyTest
-
*.pkg.Test*
: all classes in packagepkg
(regardless of the parent packages) starting withTest
-
MyTest.test*
: all classes whose simple name isMyTest
, and in them, only methods starting withtest
-
com.example.IntegTest.fast*
: the classcom.example.IntegTest
, and in it, only methods starting withfast
7. Proyectos multimodulares
Tenga en cuenta que las pruebas continuas admiten proyectos multimódulo, por lo que las pruebas en módulos distintos de la aplicación pueden seguir ejecutándose cuando se modifiquen los archivos. Los módulos que se ejecutan pueden controlarse mediante la configuración, como se indica a continuación.
Está activada por defecto, y puede desactivarse a través de quarkus.test.only-test-application-module=true
.
8. Configuración de las pruebas continuas
Las pruebas continuas admiten múltiples opciones de configuración que pueden utilizarse para limitar las pruebas que se ejecutan y controlar la salida. Las propiedades de configuración se muestran a continuación:
Propiedad de configuración corregida en tiempo de compilación - Todas las demás propiedades de configuración se pueden sobrescribir en tiempo de ejecución.
Configuration property |
Tipo |
Por defecto |
---|---|---|
If continuous testing is enabled. The default value is 'paused', which will allow you to start testing from the console or the Dev UI, but will not run tests on startup. If this is set to 'enabled' then testing will start as soon as the application has started. If this is 'disabled' then continuous testing is not enabled, and can’t be enabled without restarting the application. Environment variable: Show more |
|
|
If output from the running tests should be displayed in the console. Environment variable: Show more |
boolean |
|
The FQCN of the JUnit Environment variable: Show more |
string |
|
Tags that should be included for continuous testing. This supports JUnit Tag Expressions. Environment variable: Show more |
list of string |
|
Tags that should be excluded by default with continuous testing. This is ignored if include-tags has been set. Defaults to 'slow'. This supports JUnit Tag Expressions. Environment variable: Show more |
list of string |
|
Tests that should be included for continuous testing. This is a regular expression and is matched against the test class name (not the file name). Environment variable: Show more |
string |
|
Tests that should be excluded with continuous testing. This is a regular expression and is matched against the test class name (not the file name). This is ignored if include-pattern has been set. Environment variable: Show more |
string |
|
Test engine ids that should be included for continuous testing. Environment variable: Show more |
list of string |
|
Test engine ids that should be excluded by default with continuous testing. This is ignored if include-engines has been set. Environment variable: Show more |
list of string |
|
Changes tests to use the 'flat' ClassPath used in Quarkus 1.x versions. This means all Quarkus and test classes are loaded in the same ClassLoader, however it means you cannot use continuous testing. Note that if you find this necessary for your application then you may also have problems running in development mode, which cannot use a flat class path. Environment variable: Show more |
boolean |
|
The profile to use when testing using Environment variable: Show more |
string |
|
A comma separated list of profiles (dev, test, prod or custom profiles) to use when testing using @QuarkusTest Environment variable: Show more |
list of string |
|
The tags this profile is associated with. When the Environment variable: Show more |
list of string |
|
Controls the container network to be used when @QuarkusIntegration needs to launch the application in a container. This setting only applies if Quarkus does not need to use a shared network - which is the case if DevServices are used when running the test. Environment variable: Show more |
string |
|
Set additional ports to be exposed when @QuarkusIntegration needs to launch the application in a container. Environment variable: Show more |
Map<String,String> |
|
A set of labels to add to the launched container Environment variable: Show more |
Map<String,String> |
|
A set of volume mounts to add to the launched container Environment variable: Show more |
Map<String,String> |
|
Additional launch parameters to be used when Quarkus launches the produced artifact for Environment variable: Show more |
string |
|
Additional environment variables to be set in the process that Environment variable: Show more |
Map<String,String> |
|
Used in Environment variable: Show more |
|
|
Configures the hang detection in @QuarkusTest. If no activity happens (i.e. no test callbacks are called) over this period then QuarkusTest will dump all threads stack traces, to help diagnose a potential hang. Note that the initial timeout (before Quarkus has started) will only apply if provided by a system property, as it is not possible to read all config sources until Quarkus has booted. Environment variable: Show more |
|
|
The type of test to run, this can be either: quarkus-test: Only runs Environment variable: Show more |
|
|
If this is true then only the tests from the main application module will be run (i.e. the module that is currently running mvn quarkus:dev). If this is false then tests from all dependency modules will be run as well. Environment variable: Show more |
boolean |
|
Modules that should be included for continuous testing. This is a regular expression and is matched against the module groupId:artifactId. Environment variable: Show more |
string |
|
Modules that should be excluded for continuous testing. This is a regular expression and is matched against the module groupId:artifactId. This is ignored if include-module-pattern has been set. Environment variable: Show more |
string |
|
If the test callbacks should be invoked for the integration tests (tests annotated with Environment variable: Show more |
boolean |
|
Used to override the artifact type against which a Allowed values are: jar, native Environment variable: Show more |
string |
About the Duration format
To write duration values, use the standard You can also use a simplified format, starting with a number:
In other cases, the simplified format is translated to the
|