第 4 章 将 URL 注入测试
如果要使用其他客户端,请使用 Quarkus @TestHTTPResource 注释直接将要测试的应用 URL 注入测试类的字段中。此字段可以是 字符串、URL 或 URI 类型。您还可以在此注解中提供测试路径。在这一实践中,您将编写一个加载静态资源的简单测试。
流程
使用以下内容创建
src/main/resources/META-INF/resources/index.html文件:<html> <head> <title>Testing Guide</title> </head> <body> Information about testing </body> </html>使用以下内容创建
StaticContentTest.java文件来测试index.html是否被正确提供: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
@TestHTTPResource注释允许您直接注入 Quarkus 实例的 URL。注解的值是 URL 的路径组件。