////
This guide is maintained in the main Quarkus repository
and pull requests should be submitted there:
https://github.com/quarkusio/quarkus/tree/master/docs/src/main/asciidoc
////
= Quarkus - Testing Your Application

include::./attributes.adoc[]

:toc: macro
:toclevels: 4
:doctype: book
:icons: font
:docinfo1:

:numbered:
:sectnums:
:sectnumlevels: 4


Learn how to test your Quarkus Application.
This guide covers:

* Testing in JVM mode
* Testing in native mode
* Injection of resources into tests

== Prerequisites

To complete this guide, you need:

* less than 15 minutes
* an IDE
* JDK 1.8+ installed with `JAVA_HOME` configured appropriately
* Apache Maven {maven-version}
* The completed greeter application from the link:getting-started[Getting Started Guide]

== Architecture

In this guide, we expand on the initial test that was created as part of the Getting Started Guide.
We cover injection into tests and also how to test native executables.

== Solution

We recommend that you follow the instructions in the next sections and create the application step by step.
However, you can go right to the completed example.

Clone the Git repository: `git clone {quickstarts-clone-url}`, or download an {quickstarts-archive-url}[archive].

The solution is located in the `getting-started-testing` directory.

This guide assumes you already have the completed application from the `getting-started` directory.

== Recap of HTTP based Testing in JVM mode

If you have started from the Getting Started example you should already have a completed test, including the correct
`pom.xml` setup.

In the `pom.xml` file you should see 2 test dependencies:

[source,xml,subs=attributes+]
----
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-junit5</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <scope>test</scope>
</dependency>
----

`quarkus-junit5` is required for testing, as it provides the `@QuarkusTest` annotation that controls the testing framework.
`rest-assured` is not required but is a convenient way to test HTTP endpoints, we also provide integration that automatically
sets the correct URL so no configuration is required.

Because we are using JUnit 5, the version of the https://maven.apache.org/surefire/maven-surefire-plugin/[Surefire Maven Plugin]
must be set, as the default version does not support Junit 5:

[source,xml,subs=attributes+]
----
<plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>${surefire-plugin.version}</version>
    <configuration>
       <systemProperties>
          <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
       </systemProperties>
    </configuration>
</plugin>
----

We also set the `java.util.logging` system property to make sure tests will use the correct logmanager.

The project should also contain a simple test:

[source,java]
----
package org.acme.getting.started.testing;

import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;

import java.util.UUID;

import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.is;

@QuarkusTest
public class GreetingResourceTest {

    @Test
    public void testHelloEndpoint() {
        given()
          .when().get("/hello")
          .then()
             .statusCode(200)
             .body(is("hello"));
    }

    @Test
    public void testGreetingEndpoint() {
        String uuid = UUID.randomUUID().toString();
        given()
          .pathParam("name", uuid)
          .when().get("/hello/greeting/{name}")
          .then()
            .statusCode(200)
            .body(is("hello " + uuid));
    }

}
----

This test uses HTTP to directly test our REST endpoint. When the test is run the application will be started before
the test is run.

=== Controlling the test port

While Quarkus will listen on port `8080` by default, when running tests it defaults to `8081`. This allows you to run
tests while having the application running in parallel.

[TIP]
.Changing the test port
====
You can configure the port used by tests by configuring `quarkus.http.test-port` in your `application.properties`:
[source]
----
quarkus.http.test-port=8083
----
====

Quarkus also provides RestAssured integration that updates the default port used by RestAssured before the tests are run,
so no additional configuration should be required.

=== Injecting a URI

It is also possible to directly inject the URL into the test which can make is easy to use a different client. This is
done via the `@TestHTTPResource` annotation.

Let's write a simple test that shows this off to load some static resources. First create a simple HTML file in
`src/main/resources/META-INF/resources/index.html` :


[source,xml]
----
<html>
    <head>
        <title>Testing Guide</title>
    </head>
    <body>
        Information about testing
    </body>
</html>
----

We will create a simple test to ensure that this is being served correctly:


[source,java]
----
package org.acme.getting.started.testing;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;

@QuarkusTest
public class StaticContentTest {

    @TestHTTPResource("index.html") // <1>
    URL url;

    @Test
    public void testIndexHtml() throws Exception {
        try (InputStream in = url.openStream()) {
            String contents = readStream(in);
            Assertions.assertTrue(contents.contains("<title>Testing Guide</title>"));
        }
    }

    private static String readStream(InputStream in) throws IOException {
        byte[] data = new byte[1024];
        int r;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        while ((r = in.read(data)) > 0) {
            out.write(data, 0, r);
        }
        return new String(out.toByteArray(), StandardCharsets.UTF_8);
    }
}
----
<1> This annotation allows you to directly inject the URL of the Quarkus instance, the value of the annotation will be the path component of the URL

For now `@TestHTTPResource` allows you to inject `URI`, `URL` and `String` representations of the URL.

== Injection into tests

So far we have only covered integration style tests that test the app via HTTP endpoints, but what if we want to do unit
testing and test our beans directly?

Quarkus supports this by allowing you to inject CDI beans into your tests via the `@Inject` annotation (in fact, tests in
Quarkus are full CDI beans, so you can use all CDI functionality). Let's create a simple test that tests the greeting
service directly without using HTTP:


[source,java]
----
package org.acme.getting.started.testing;

import javax.inject.Inject;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import io.quarkus.test.junit.QuarkusTest;

@QuarkusTest
public class GreetingServiceTest {

    @Inject //<1>
    GreetingService service;

    @Test
    public void testGreetingService() {
        Assertions.assertEquals("hello Quarkus", service.greeting("Quarkus"));
    }
}
----
<1> The `GreetingService` bean will be injected into the test

== Applying Interceptors to Tests

As mentioned above Quarkus tests are actually full CDI beans, and as such you can apply CDI interceptors as you would
normally. As an example, if you want a test method to run within the context of a transaction you can simply apply the
`@Transactional` annotation to the method and the transaction interceptor will handle it.

In addition to this you can also create your own test stereotypes. For example we could create a `@TransactionalQuarkusTest`
as follows:

[source,java]
----
@QuarkusTest
@Stereotype
@Transactional
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TransactionalQuarkusTest {
}
----

If we then apply this annotation to a test class it will act as if we had applied both the `@QuarkusTest` and
`@Transactional` annotations, e.g.:


[source,java]
----
@TransactionalQuarkusTest
public class TestStereotypeTestCase {

    @Inject
    UserTransaction userTransaction;

    @Test
    public void testUserTransaction() throws Exception {
        Assertions.assertEquals(Status.STATUS_ACTIVE, userTransaction.getStatus());
    }

}
----


== Mock Support

Quarkus supports the use of mock objects using the CDI `@Alternative` mechanism.
To use this simply override the bean you wish to mock with a class in the `src/test/java` directory, and put the `@Alternative` and `@Priority(1)` annotations on the bean. 
Alternatively, a convenient `io.quarkus.test.Mock` stereotype annotation could be used.
This built-in stereotype declares `@Alternative`, `@Priority(1)` and `@Dependent`. 
For example if I have the following service:

[source,java]
----
@ApplicationScoped
public class ExternalService {

    public String service() {
        return "external";
    }

}
----

I could mock it with the following class in `src/test/java`:

[source,java]
----
@Mock
@ApplicationScoped <1>
public class MockExternalService extends ExternalService {

    @Override
    public String service() {
        return "mock";
    }
}
----
<1> Overrides the `@Dependent` scope declared on the `@Mock` stereotype.

It is important that the alternative be present in the `src/test/java` directory rather than `src/main/java`, as otherwise
it will take effect all the time, not just when testing.

Note that at present this approach does not work with native image testing, as this would required the test alternatives
to be baked into the native image.

== Test Bootstrap Configuration Options

There are a few system properties that can be used to tune the bootstrap of the test, specifically its classpath.

* *quarkus-bootstrap-offline* - _(boolean)_ if set by the user, depending on the value, will enable or disable the offline mode for the Maven artifact resolver used by the bootstrap to resolve the deployment dependencies of the Quarkus extensions used in the test. If the property is not set to any value, the artifact resolver will use the system's default (user's `settings.xml`).

* *quarkus-workspace-discovery* - _(boolean)_ controls whether the bootstrap artifact resolver should look for the test dependencies among the projects in the current workspace and use their output (`classes`) directories when setting up the classpath for the test to run. *The default value is true*.

* *quarkus-classpath-cache* - _(boolean)_ enables or disables the bootstrap classpath cache. With the number of the project dependencies growing, the dependency resolution will take more time which could at some point become annoying. The Quarkus bootstrap allows to cache the resolved classpath and store it in the output directory of the project. The cached classpath will be recalculated only after any of the `pom.xml` file in the workspace has been changed. The cache directory is also removed each time the project's output directory is cleaned, of course. *The default value is true*.

== Native Executable Testing

It is also possible to test native executables using `@NativeImageTest`. This supports all the features mentioned in this
guide except injecting into tests (and the native executable runs in a separate non-JVM process this is not really possible).


This is covered in the link:building-native-image[Native Executable Guide].
