Quarkus TDD 工作流程
用於 Quarkus 3.x 服務的 TDD 指南,達到 80% 以上的覆蓋率(單元測試 + 整合測試)。針對使用 Apache Camel 的事件驅動架構進行最佳化。
使用時機
- 新功能或 REST 端點
- 錯誤修正或重構
- 新增資料存取邏輯、安全規則或反應式串流
- 測試 Apache Camel 路由和事件處理器
- 使用 RabbitMQ 測試事件驅動服務
- 測試條件流程邏輯
- 驗證 CompletableFuture 非同步操作
- 測試 LogContext 傳遞
工作流程
- 先撰寫測試(應會失敗)
- 實作最少程式碼以通過測試
- 測試通過後進行重構
- 使用 JaCoCo 強制覆蓋率(目標 80% 以上)
使用 @Nested 組織的單元測試
遵循此結構化方法來撰寫全面且可讀的測試:
@ExtendWith(MockitoExtension.class)
@DisplayName("OrderService 單元測試")
class OrderServiceTest {
@Mock
private OrderRepository orderRepository;
@Mock
private EventService eventService;
@Mock
private FulfillmentPublisher fulfillmentPublisher;
@InjectMocks
private OrderService orderService;
private CreateOrderCommand validCommand;
@BeforeEach
void setUp() {
validCommand = new CreateOrderCommand(
"customer-123",
List.of(new OrderLine("sku-123", 2))
);
}
@Nested
@DisplayName("createOrder 的測試")
class CreateOrder {
@Test
@DisplayName("應持久化訂單並發布履行事件")
void givenValidCommand_whenCreateOrder_thenPersistsAndPublishes() {
// 安排
doNothing().when(orderRepository).persist(any(Order.class));
// 動作
OrderReceipt receipt = orderService.createOrder(validCommand);
// 斷言
assertThat(receipt).isNotNull();
assertThat(receipt.customerId()).isEqualTo("customer-123");
verify(orderRepository).persist(any(Order.class));
verify(fulfillmentPublisher).publishAsync(receipt);
verify(eventService).createSuccessEvent(receipt, "ORDER_CREATED");
}
@Test
@DisplayName("應拒絕缺少客戶 ID")
void givenMissingCustomerId_whenCreateOrder_thenThrowsBadRequest() {
// 安排
CreateOrderCommand invalid = new CreateOrderCommand("", validCommand.lines());
// 動作與斷言
WebApplicationException exception = assertThrows(
WebApplicationException.class,
() -> orderService.createOrder(invalid)
);
assertThat(exception.getResponse().getStatus()).isEqualTo(400);
verify(orderRepository, never()).persist(any(Order.class));
verify(fulfillmentPublisher, never()).publishAsync(any());
}
@Test
@DisplayName("持久化失敗時應記錄錯誤事件")
void givenPersistenceFailure_whenCreateOrder_thenRecordsErrorEvent() {
// 安排
doThrow(new PersistenceException("資料庫不可用"))
.when(orderRepository).persist(any(Order.class));
// 動作與斷言
PersistenceException exception = assertThrows(
PersistenceException.class,
() -> orderService.createOrder(validCommand)
);
assertThat(exception.getMessage()).contains("資料庫不可用");
verify(eventService).createErrorEvent(
eq(validCommand),
eq("ORDER_CREATE_FAILED"),
contains("資料庫不可用")
);
verify(fulfillmentPublisher, never()).publishAsync(any());
}
@Test
@DisplayName("應拒絕 null 命令")
void givenNullCommand_whenCreateOrder_thenThrowsNullPointerException() {
// 動作與斷言
assertThrows(
NullPointerException.class,
() -> orderService.createOrder(null)
);
verify(orderRepository, never()).persist(any(Order.class));
}
}
}
關鍵測試模式
- @Nested 類別:按測試方法分組
- @DisplayName:為測試報告提供可讀的測試描述
- 命名慣例:使用
givenX_whenY_thenZ以增進清晰度 - AAA 模式:明確標示
// 安排、// 動作、// 斷言註解 - @BeforeEach:設定共用測試資料以減少重複
- assertDoesNotThrow:測試成功情境,無需捕捉例外
- assertThrows:使用 AssertJ 測試例外情境並驗證訊息
- 全面覆蓋:測試快樂路徑、null 輸入、邊界情況、例外狀況
- 驗證互動:使用 Mockito
verify()確保方法被正確呼叫 - 從不驗證:使用
never()確保方法在錯誤情境中不被呼叫
測試 Camel 路由
@QuarkusTest
@DisplayName("商務規則 Camel 路由測試")
class BusinessRulesRouteTest {
@Inject
CamelContext camelContext;
@Inject
ProducerTemplate producerTemplate;
@InjectMock
EventService eventService;
@InjectMock
DocumentValidator documentValidator;
private BusinessRulesPayload testPayload;
@BeforeEach
void setUp() {
// 安排 - 測試資料
testPayload = new BusinessRulesPayload();
testPayload.setDocumentId(1L);
testPayload.setFlowProfile(FlowProfile.BASIC);
}
@Nested
@DisplayName("business-rules-publisher 路由的測試")
class BusinessRulesPublisher {
@Test
@DisplayName("應成功發布訊息到 RabbitMQ")
void givenValidPayload_whenPublish_thenMessageSentToQueue() throws Exception {
// 安排
MockEndpoint mockRabbitMQ = camelContext.getEndpoint("mock:rabbitmq", MockEndpoint.class);
mockRabbitMQ.expectedMessageCount(1);
// 用 mock 取代真實端點以進行測試
camelContext.getRouteController().stopRoute("business-rules-publisher");
AdviceWith.adviceWith(camelContext, "business-rules-publisher", advice -> {
advice.replaceFromWith("direct:business-rules-publisher");
advice.weaveByToString(".*spring-rabbitmq.*").replace().to("mock:rabbitmq");
});
camelContext.getRouteController().startRoute("business-rules-publisher");
// 動作
producerTemplate.sendBody("direct:business-rules-publisher", testPayload);
// 斷言 — 主體是經過 .marshal().json(JsonLibrary.Jackson) 後的 JSON 字串
mockRabbitMQ.assertIsSatisfied(5000);
assertThat(mockRabbitMQ.getExchanges()).hasSize(1);
String body = mockRabbitMQ.getExchanges().get(0).getIn().getBody(String.class);
assertThat(body).contains("\"documentId\":1");
}
@Test
@DisplayName("應處理序列化為 JSON")
void givenPayload_whenPublish_thenMarshalledToJson() throws Exception {
// 安排
MockEndpoint mockMarshal = new MockEndpoint("mock:marshal");
camelContext.addEndpoint("mock:marshal", mockMarshal);
mockMarshal.expectedMessageCount(1);
camelContext.getRouteController().stopRoute("business-rules-publisher");
AdviceWith.adviceWith(camelContext, "business-rules-publisher", advice -> {
advice.weaveAddLast().to("mock:marshal");
});
camelContext.getRouteController().startRoute("business-rules-publisher");
// 動作
producerTemplate.sendBody("direct:business-rules-publisher", testPayload);
// 斷言
mockMarshal.assertIsSatisfied(5000);
String body = mockMarshal.getExchanges().get(0).getIn().getBody(String.class);
assertThat(body).contains("\"documentId\":1");
assertThat(body).contains("\"flowProfile\":\"BASIC\"");
}
}
@Nested
@DisplayName("document-processing 路由的測試")
class DocumentProcessing {
@Test
@DisplayName("應將發票類型路由到正確的處理器")
void givenInvoiceType_whenProcess_thenRoutesToInvoiceProcessor() throws Exception {
// 安排
MockEndpoint mockInvoice = camelContext.getEndpoint("mock:invoice", MockEndpoint.class);
mockInvoice.expectedMessageCount(1);
camelContext.getRouteController().stopRoute("document-processing");
AdviceWith.adviceWith(camelContext, "document-processing", advice -> {
advice.weaveByToString(".*direct:process-invoice.*").replace().to("mock:invoice");
});
camelContext.getRouteController().startRoute("document-processing");
// 動作
producerTemplate.sendBodyAndHeader("direct:process-document",
testPayload, "documentType", "INVOICE");
// 斷言
mockInvoice.assertIsSatisfied(5000);
}
@Test
@DisplayName("驗證錯誤時應優雅處理")
void givenValidationError_whenProcess_thenRoutesToErrorHandler() throws Exception {
// 安排
MockEndpoint mockError = camelContext.getEndpoint("mock:error", MockEndpoint.class);
mockError.expectedMessageCount(1);
camelContext.getRouteController().stopRoute("document-processing");
AdviceWith.adviceWith(camelContext, "document-processing", advice -> {
advice.weaveByToString(".*direct:validation-error-handler.*")
.replace().to("mock:error");
});
camelContext.getRouteController().startRoute("document-processing");
// Mock 驗證器 bean 以拋出例外
when(documentValidator.validate(any())).thenThrow(new ValidationException(\