Communitygithub.com

quarkus-tdd

針對 Quarkus 3.x LTS 的測試驅動開發,使用 JUnit 5、Mockito、REST Assured、Camel 測試及 JaCoCo。適用於新增功能、修正錯誤或重構事件驅動服務。

quarkus-tdd 是什麼?

此技能專為 Quarkus 3.x LTS 服務提供測試驅動開發(TDD)工作流程,目標是達成 80% 以上的程式碼覆蓋率(包含單元測試與整合測試)。技能特別針對使用 Apache Camel 的事件驅動架構進行最佳化,支援測試 Camel 路由、RabbitMQ 事件處理、條件流程邏輯、CompletableFuture 非同步操作以及 LogContext 傳播。工作流程遵循經典的 TDD 循環:先撰寫測試(應失敗),再實作最小程式碼使其通過,最後重構並維持測試通過,並透過 JaCoCo 強制覆蓋率目標。實務上建議使用 @Nested 類別按方法組織測試、採用 givenX_whenY_thenZ 命名慣例與 AAA(安排-執行-斷言)模式,並善用 Mockito 的 verify() 與 never() 驗證互動。技能也提供了完整的範例程式碼,包括 REST 端點測試、Camel 路由測試(使用 AdviceWith 模擬端點)以及負面情境(含例外處理、空值輸入、資料庫失敗等)的測試模式。此技能支援 QuarkusTest 整合測試與 MockitoExtension 單元測試,適合所有需要以 TDD 方式開發 Quarkus 微服務或事件驅動系統的開發者。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/quarkus-tdd

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Quarkus TDD 工作流程

用於 Quarkus 3.x 服務的 TDD 指南,達到 80% 以上的覆蓋率(單元測試 + 整合測試)。針對使用 Apache Camel 的事件驅動架構進行最佳化。

使用時機

  • 新功能或 REST 端點
  • 錯誤修正或重構
  • 新增資料存取邏輯、安全規則或反應式串流
  • 測試 Apache Camel 路由和事件處理器
  • 使用 RabbitMQ 測試事件驅動服務
  • 測試條件流程邏輯
  • 驗證 CompletableFuture 非同步操作
  • 測試 LogContext 傳遞

工作流程

  1. 先撰寫測試(應會失敗)
  2. 實作最少程式碼以通過測試
  3. 測試通過後進行重構
  4. 使用 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));
    }
  }
}

關鍵測試模式

  1. @Nested 類別:按測試方法分組
  2. @DisplayName:為測試報告提供可讀的測試描述
  3. 命名慣例:使用 givenX_whenY_thenZ 以增進清晰度
  4. AAA 模式:明確標示 // 安排、// 動作、// 斷言 註解
  5. @BeforeEach:設定共用測試資料以減少重複
  6. assertDoesNotThrow:測試成功情境,無需捕捉例外
  7. assertThrows:使用 AssertJ 測試例外情境並驗證訊息
  8. 全面覆蓋:測試快樂路徑、null 輸入、邊界情況、例外狀況
  9. 驗證互動:使用 Mockito verify() 確保方法被正確呼叫
  10. 從不驗證:使用 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(\

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

相關技能