Chapter 4. Injecting a URL into a test

If you want to use a different client, use the Quarkus @TestHTTPResource annotation to directly inject the URL of the application to be tested into a field on the test class. This field can be of the type String, URL, or URI. You can also provide the test path in this annotation. In this exercise, you will write a simple test that loads static resources.

Procedure

  1. Create the src/main/resources/META-INF/resources/index.html file with the following content:

    <html>
        <head>
            <title>Testing Guide</title>
        </head>
        <body>
            Information about testing
        </body>
    </html>
  2. Create the StaticContentTest.java file with the following content to test that index.html is being served correctly:

    package org.acme.quickstart;
    
    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
    The @TestHTTPResource annotation enables you to directly inject the URL of the Quarkus instance. The value of the annotation is the path component of the URL.