Quarkus命令模式应用MockServer注入异常求助
Quarkus命令模式应用MockServer测试配置方案
核心问题原因
@QuarkusMainTest启动的是独立的应用进程,测试类中直接声明的@QuarkusTestResource资源与应用进程隔离,无法直接共享MockServer的URL配置,必须通过Test Profile将MockServer的配置传递到应用运行时环境中。
具体实现步骤
1. 定义Test Profile类
实现QuarkusTestProfile接口,负责启动MockServer资源并将其URL注入到应用配置中:
import io.quarkus.test.junit.QuarkusTestProfile; import java.util.Map; public class MockServerTestProfile implements QuarkusTestProfile { @Override public Map<String, String> getConfigOverrides() { // 获取MockServer实际启动的端口(根据你使用的MockServer实现调整获取逻辑) String mockServerPort = System.getProperty("mock.server.port", "8081"); String mockServerUrl = String.format("http://localhost:%s", mockServerPort); // 覆盖应用中审计REST服务的配置项,替换为你的实际配置key return Map.of("audit.rest.base-url", mockServerUrl); } @Override public Class<?>[] testResources() { // 指定要启动的MockServer资源类 return new Class[]{MockServer.class}; } }
2. 修改测试类使用Test Profile
替换原@QuarkusTestResource注解为@TestProfile,确保应用启动时加载Test Profile的配置:
import io.quarkus.test.junit.QuarkusMainTest; import io.quarkus.test.junit.TestProfile; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; @QuarkusMainTest @TestProfile(MockServerTestProfile.class) public class BatchCommandTest { @Test @Launch() public void testLaunchCommand(LaunchResult result) { // 提前配置MockServer的响应规则(确保和应用请求路径匹配) setupMockPositiveSubmitLoggingEvent(); assertEquals(0, result.exitCode()); assertTrue(result.getOutput().contains("BatchJobInterface")); } private void setupMockPositiveSubmitLoggingEvent() { // 示例:配置MockServer接收审计请求并返回成功响应 // 替换为你的MockServer客户端配置逻辑,比如WireMock的stub规则 // logMockServerClient.when(request().withPath("/audit/submit")) // .respond(response().withStatusCode(200)); } }
3. 应用代码读取配置
确保应用中调用审计REST服务的组件,读取Test Profile注入的配置:
import jakarta.enterprise.context.ApplicationScoped; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.eclipse.microprofile.rest.client.inject.RestClient; @ApplicationScoped public class AuditClient { @RestClient private AuditRestClient auditRestClient; // 注入Test Profile传递的MockServer URL @ConfigProperty(name = "audit.rest.base-url") private String auditBaseUrl; public void sendAuditLog(AuditLog log) { // 使用配置的URL调用审计服务,或确保RestClient的baseUri指向该配置 auditRestClient.submitLog(log); } }
关键注意事项
- 确保MockServer资源类能将启动后的端口暴露为系统属性或可访问的变量,否则Test Profile无法获取正确的URL
- 测试前配置MockServer响应规则时,要与应用实际请求的路径、方法完全匹配
- 避免手动在
application.properties中硬编码MockServer URL,Test Profile会自动覆盖配置,保证环境一致性
内容的提问来源于stack exchange,提问作者Avara
相关产品推荐
相关产品推荐

