The English version of quarkus.io is the official project site. Translated sites are community supported on a best-effort basis.

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 11+ installed with JAVA_HOME configured appropriately

  • Apache Maven 3.8.8

  • 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, en las que 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 de código. Quarkus detecta qué pruebas cubren qué código, y utiliza esta información para ejecutar sólo las pruebas pertinentes cuando se cambia el código.

3. Solución

Inicie la aplicación "Getting Started " (o cualquier otra aplicación) utilizando:

CLI
quarkus dev
Maven
./mvnw quarkus:dev
Gradle
./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. Deberías ver el cambio de estado en la parte inferior de la pantalla mientras se ejecutan, y debería 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 quiere que las pruebas continuas se inicien automáticamente, puede configurar quarkus.test.continuous-testing=enabled en application.properties. Si no quiere que se inicien, puede cambiar esta opción a disabled.

Ahora puedes empezar a hacer cambios en tu aplicación. Entra en GreetingResource y cambia el endpoint hello para que devuelva "hello world", y guarda el archivo. Quarkus debería volver a ejecutar inmediatamente la prueba, y deberías 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

Hay varias teclas de acceso directo que puede utilizar para controlar las pruebas continuas. Al pulsar 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 "sólo fallidas" sólo ejecutará las pruebas que hayan fallado previamente, incluso si otras pruebas se verían normalmente afectadas por un cambio de código. Esto puede ser útil si estás modificando código que es utilizado por muchas pruebas, pero sólo quieres centrarte en la depuración de la que falla.

[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 la 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 en modo dev 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á deshabilitada, la salida filtrada se guarda y se puede ver en la interfaz de usuario de desarrollo.

[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 da 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 en busca 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 funcionará incluso si la recarga en vivo está deshabilitada.

5. Pruebas continuas sin modo de desarrollo

Es posible ejecutar pruebas continuas sin iniciar el modo dev. Esto puede ser útil si el modo de desarrollo va a interferir con sus pruebas (por ejemplo, ejecutando wiremock en el mismo puerto), o si sólo quiere desarrollar utilizando pruebas. Para iniciar el modo de pruebas continuas ejecute mvn quarkus:test.

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. Multi-module Projects

Tenga en cuenta que las pruebas continuas soportan proyectos multimódulo, por lo que las pruebas en los módulos que no sean la aplicación pueden seguir ejecutándose cuando se cambien los archivos. Los módulos que se ejecutan pueden ser controlados usando 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.

7. 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 para controlar la salida. Las propiedades de configuración se muestran a continuación:

Configuration property fixed at build time - All other configuration properties are overridable at runtime

Configuration property

Type

Default

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: QUARKUS_TEST_CONTINUOUS_TESTING

paused, enabled, disabled

paused

If output from the running tests should be displayed in the console.

Environment variable: QUARKUS_TEST_DISPLAY_TEST_OUTPUT

boolean

false

Tags that should be included for continuous testing.

Environment variable: QUARKUS_TEST_INCLUDE_TAGS

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'

Environment variable: QUARKUS_TEST_EXCLUDE_TAGS

list of string

slow

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: QUARKUS_TEST_INCLUDE_PATTERN

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: QUARKUS_TEST_EXCLUDE_PATTERN

string

.*\.IT[^.]+|.*IT|.*ITCase

Test engine ids that should be included for continuous testing.

Environment variable: QUARKUS_TEST_INCLUDE_ENGINES

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: QUARKUS_TEST_EXCLUDE_ENGINES

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: QUARKUS_TEST_FLAT_CLASS_PATH

boolean

false

The profile to use when testing the native image

Environment variable: QUARKUS_TEST_NATIVE_IMAGE_PROFILE

string

prod

The profile to use when testing using @QuarkusIntegrationTest

Environment variable: QUARKUS_TEST_INTEGRATION_TEST_PROFILE

string

prod

The profile (dev, test or prod) to use when testing using @QuarkusTest

Environment variable: QUARKUS_TEST_PROFILE

string

test

The tags this profile is associated with. When the quarkus.test.profile.tags System property is set (its value is a comma separated list of strings) then Quarkus will only execute tests that are annotated with a @TestProfile that has at least one of the supplied (via the aforementioned system property) tags.

Environment variable: QUARKUS_TEST_PROFILE_TAGS

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: QUARKUS_TEST_CONTAINER_NETWORK

string

Additional launch parameters to be used when Quarkus launches the produced artifact for @QuarkusIntegrationTest When the artifact is a jar, this string is passed right after the java command. When the artifact is a container, this string is passed right after the docker run command. When the artifact is a native binary, this string is passed right after the native binary name.

Environment variable: QUARKUS_TEST_ARG_LINE

list of string

Used in @QuarkusIntegrationTest to determine how long the test will wait for the application to launch

Environment variable: QUARKUS_TEST_WAIT_TIME

Duration

PT1M

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: QUARKUS_TEST_HANG_DETECTION_TIMEOUT

Duration

10M

The type of test to run, this can be either: quarkus-test: Only runs @QuarkusTest annotated test classes unit: Only runs classes that are not annotated with @QuarkusTest all: Runs both, running the unit tests first

Environment variable: QUARKUS_TEST_TYPE

unit, quarkus-test, all

all

If a class matches this pattern then it will be cloned into the Quarkus ClassLoader even if it is in a parent first artifact. This is important for collections which can contain objects from the Quarkus ClassLoader, but for most parent first classes it will just cause problems.

Environment variable: QUARKUS_TEST_CLASS_CLONE_PATTERN

string

java\..*

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: QUARKUS_TEST_ONLY_TEST_APPLICATION_MODULE

boolean

false

Modules that should be included for continuous testing. This is a regular expression and is matched against the module groupId:artifactId.

Environment variable: QUARKUS_TEST_INCLUDE_MODULE_PATTERN

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: QUARKUS_TEST_EXCLUDE_MODULE_PATTERN

string

If the test callbacks should be invoked for the integration tests (tests annotated with @QuarkusIntegrationTest).

Environment variable: QUARKUS_TEST_ENABLE_CALLBACKS_FOR_INTEGRATION_TESTS

boolean

false

Set additional ports to be exposed when @QuarkusIntegration needs to launch the application in a container.

Environment variable: QUARKUS_TEST_CONTAINER_ADDITIONAL_EXPOSED_PORTS

Map<String,String>

About the Duration format

El formato de las duraciones utiliza el formato estándar java.time.Duration. Puede obtener más información al respecto en Duration#parse() javadoc.

También puede proporcionar valores de duración que empiecen por un número. En este caso, si el valor consiste sólo en un número, el conversor trata el valor como segundos. En caso contrario, PT se antepone implícitamente al valor para obtener un formato estándar java.time.Duration.