{"slug":"contract-testing","title":"contract-testing","summary":"Use when authoring OpenAPI/AsyncAPI contracts, generating Microcks samples, setting up Testcontainers mocks, verifying provider contracts, or bridging API contracts across DESIGN → DISTILL → DELIVER phases.","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-11-29T00:42:30.056305Z","repo":{"url":"https://github.com/SebastienDegodez/skraft-plugin","stars":17,"forks":3,"license":"GPL-3.0","updatedAt":"2026-11-29T00:18:21Z"},"bodyHtml":"<hr>\n<h2>name: contract-testing\ndescription: &gt;\nUse when authoring OpenAPI/AsyncAPI contracts, generating Microcks samples,\nsetting up Testcontainers mocks, verifying provider contracts, or bridging\nAPI contracts across DESIGN → DISTILL → DELIVER phases.</h2>\n<h1>Contract Testing</h1>\n<h2>Overview</h2>\n<p>Contract-first API development spans three SDLC phases. Each phase produces specific artifacts consumed by the next.</p>\n<pre><code>DESIGN                      DISTILL                          DELIVER\nOpenAPI / AsyncAPI    →     Microcks samples           →     Testcontainers mocks\ncontracts/{api}.yaml        .apiexamples.yaml                MicrocksContainer\n                            .apimetadata.yaml                + TestEndpointAsync()\n</code></pre>\n<p><strong>Artifact path convention:</strong></p>\n<ul>\n<li>DESIGN  → <code>.copilot-tracking/skraft-plans/{projectSlug}/details/{date}/contracts/{api-name}.yaml</code></li>\n<li>DISTILL → <code>.copilot-tracking/skraft-plans/{projectSlug}/details/{date}/contracts/{api-name}.apiexamples.yaml</code>\n<code>.copilot-tracking/skraft-plans/{projectSlug}/details/{date}/contracts/{api-name}.apimetadata.yaml</code></li>\n<li>DELIVER → Testcontainers test class imports both DISTILL artifacts</li>\n</ul>\n<p><strong>Core principle:</strong> the contract is the source of truth. Implementation is verified against it, not the other way around.</p>\n<hr>\n<h2>1. Authoring API Contracts (DESIGN phase)</h2>\n<p>Write OpenAPI 3.1 contracts in YAML. Store at <code>.copilot-tracking/skraft-plans/{projectSlug}/details/{date}/contracts/{api-name}.yaml</code>.</p>\n<p><strong>Required top-level structure:</strong></p>\n<pre><code>openapi: 3.1.0\ninfo:\n  title: {Human Readable API Name}\n  version: 1.0.0\n  description: {One sentence purpose}\npaths:\n  /resource/{id}:\n    get:\n      operationId: getResourceById\n      summary: {Brief summary}\n      parameters: [...]\n      responses:\n        \"200\":\n          description: Success\n          content:\n            application/json:\n              schema:\n                $ref: \"#/components/schemas/ResourceResponse\"\n        \"404\":\n          description: Not found\n          content:\n            application/json:\n              schema:\n                $ref: \"#/components/schemas/ErrorResponse\"\ncomponents:\n  schemas:\n    ResourceResponse:\n      type: object\n      required: [id, status]\n      properties:\n        id:\n          type: string\n        status:\n          type: string\n    ErrorResponse:\n      type: object\n      required: [code, message]\n      properties:\n        code:\n          type: string\n        message:\n          type: string\n</code></pre>\n<p><strong>Versioning rules:</strong></p>\n<ul>\n<li>Increment <code>info.version</code> on any breaking change (removed field, changed type, removed operation).</li>\n<li>Non-breaking additions (new optional field, new operation) → minor version bump.</li>\n<li>Use <code>{api-name}-v{major}.yaml</code> for major version coexistence.</li>\n</ul>\n<p><strong>File naming:</strong> kebab-case, matching the bounded context and resource. Example: <code>eligibility-check-api.yaml</code>.</p>\n<hr>\n<h2>2. Generating Microcks Samples (DISTILL phase)</h2>\n<p>Produce two files per contract:</p>\n<h3><code>.apiexamples.yaml</code> — response examples per operation</h3>\n<pre><code>apiVersion: mocks.microcks.io/v1alpha1\nkind: APIExamples\nmetadata:\n  name: \"{API Title} - {version}\"\nspec:\n  examples:\n    {operationId}:\n      \"{Example Name}\":\n        request:\n          parameters:\n            {paramName}: \"{value}\"\n          body: |\n            {JSON body if POST/PUT}\n        response:\n          code: 200\n          headers:\n            Content-Type: application/json\n          body: |\n            {\n              \"field\": \"value\"\n            }\n</code></pre>\n<p><strong>Rules:</strong></p>\n<ul>\n<li><code>metadata.name</code> must match the <code>info.title</code> + <code>info.version</code> from the OpenAPI contract exactly.</li>\n<li>One entry per operationId; multiple named examples under each operationId are supported.</li>\n<li><code>request.parameters</code> holds path and query params as string values.</li>\n<li><code>response.code</code> is an integer.</li>\n</ul>\n<h3><code>.apimetadata.yaml</code> — dispatcher configuration</h3>\n<pre><code>apiVersion: mocks.microcks.io/v1alpha1\nkind: APIMetadata\nmetadata:\n  name: \"{API Title} - {version}\"\nspec:\n  operations:\n    - name: \"{HTTP_METHOD} /path/{param}\"\n      dispatcher: JSON_BODY | JS | GROOVY\n      dispatcherRules: |\n        {dispatcher-specific rules}\n</code></pre>\n<p><strong>Dispatcher selection:</strong></p>\n<ul>\n<li><code>JSON_BODY</code> — route on a request body JSON field value. Use for simple request matching.</li>\n<li><code>JS</code> — route using a JavaScript function. Use when routing logic is conditional or multi-field.</li>\n<li><code>GROOVY</code> — route using Groovy DSL. Use for stateful mocks (in-memory counters, delay simulation).</li>\n</ul>\n<p><strong>JSON_BODY dispatcher rules format:</strong></p>\n<pre><code>exp=$.fieldName cases=VALUE_A:ExampleName1&amp;&amp;VALUE_B:ExampleName2\n</code></pre>\n<p><strong>JS dispatcher rules format:</strong></p>\n<pre><code>function dispatch(request) {\n  var body = JSON.parse(request.body);\n  if (body.field === \"value\") return \"ExampleName\";\n  return \"DefaultExample\";\n}\n</code></pre>\n<p><strong>GROOVY dispatcher rules format:</strong></p>\n<pre><code>def body = new groovy.json.JsonSlurper().parseText(request.body)\nif (body.field == \"value\") return \"ExampleName\"\nreturn \"DefaultExample\"\n</code></pre>\n<hr>\n<h2>3. Testcontainers Setup (DELIVER phase)</h2>\n<blockquote>\n<p><strong>DELIVER wiring is stack-specific — resolve it through an adapter.</strong> This skill\nowns the <em>generic, stack-agnostic</em> contract authoring (sections 1-2, 5-7) and\nthe Microcks sample formats. The concrete DELIVER recipe (baseline\n<code>WebApplicationFactory</code> + <code>HttpClient</code>, plus the optional Microcks <code>VerifyAsync</code>\nlayer) is owned per stack by the <code>contract-testing-&lt;stack&gt;</code> adapter, resolved\nvia <code>contract-testing-roster</code>. For .NET see\n<code>contract-testing-dotnet</code>. The .NET snippets\nbelow remain as the canonical reference those adapters point back to.</p>\n</blockquote>\n<p>Use the <code>Microcks.Testcontainers</code> NuGet package (it brings <code>DotNet.Testcontainers</code>\ntransitively — do not also reference the unrelated <code>Testcontainers</code>/<code>TestContainers</code>\npackages).</p>\n<p><strong>NuGet packages:</strong></p>\n<pre><code>Microcks.Testcontainers\n</code></pre>\n<p><strong>Real 0.3.4 API (used by every snippet below):</strong></p>\n<ul>\n<li><code>new MicrocksBuilder()...Build()</code> returns the container; then <code>await container.StartAsync()</code>. There is no <code>BuildAsync()</code>.</li>\n<li><code>WithMainArtifacts(params string[])</code> loads the schema + examples + metadata in ONE call (schema first). There is no singular <code>WithMainArtifact</code>.</li>\n<li><code>container.GetRestMockEndpoint(\"API Title\", \"1.0.0\")</code> returns a <code>Uri</code> (mock base URL). There is no <code>GetRestMockUrl</code>.</li>\n<li>Provider conformance is <code>container.TestEndpointAsync(TestRequest{ OPEN_API_SCHEMA })</code> (§4). <code>VerifyAsync(name, version)</code> returns a <code>bool</code> checking mock-invocation counts — a consumer-side concern, not conformance.</li>\n</ul>\n<p><strong>Consumer-side mock setup (IAsyncLifetime) — mock a downstream dependency:</strong></p>\n<pre><code>public class EligibilityApiTests : IAsyncLifetime\n{\n    private MicrocksContainer _microcks = null!;\n\n    public async Task InitializeAsync()\n    {\n        _microcks = new MicrocksBuilder()\n            .WithMainArtifacts(\n                \"contracts/eligibility-check-api.yaml\",\n                \"contracts/eligibility-check-api.apiexamples.yaml\",\n                \"contracts/eligibility-check-api.apimetadata.yaml\")\n            .Build();\n        await _microcks.StartAsync();\n    }\n\n    public async Task DisposeAsync() =&gt; await _microcks.DisposeAsync();\n\n    [Fact]\n    public async Task Should_return_eligible_driver()\n    {\n        Uri mockUrl = _microcks.GetRestMockEndpoint(\"Eligibility Check API\", \"1.0.0\");\n        // use mockUrl as the base address of the SUT's downstream HttpClient\n    }\n}\n</code></pre>\n<p><strong>WebApplicationFactory integration (consumer-side — point the SUT's downstream client at the mock):</strong></p>\n<pre><code>public class ApiFactory : WebApplicationFactory&lt;Program&gt;, IAsyncLifetime\n{\n    private MicrocksContainer _microcks = null!;\n\n    public async Task InitializeAsync()\n    {\n        _microcks = new MicrocksBuilder()\n            .WithMainArtifacts(\n                \"contracts/eligibility-check-api.yaml\",\n                \"contracts/eligibility-check-api.apiexamples.yaml\")\n            .Build();\n        await _microcks.StartAsync();\n    }\n\n    protected override void ConfigureWebHost(IWebHostBuilder builder)\n    {\n        builder.ConfigureServices(services =&gt;\n        {\n            // Point the SUT's DOWNSTREAM client at the Microcks mock endpoint.\n            Uri mockUrl = _microcks.GetRestMockEndpoint(\"Eligibility Check API\", \"1.0.0\");\n            services.AddHttpClient&lt;IEligibilityClient, EligibilityClient&gt;(\n                c =&gt; c.BaseAddress = mockUrl);\n        });\n    }\n\n    public async Task DisposeAsync()\n    {\n        await _microcks.DisposeAsync();\n        await base.DisposeAsync();\n    }\n}\n</code></pre>\n<blockquote>\n<p>A <code>WebApplicationFactory</code> works for consumer-side mocking (above) because the\nSUT calls OUT to the mock. It does NOT work for provider conformance (§4): that\nneeds Microcks to call IN to the SUT on a real TCP port, which an in-memory test\nserver does not expose.</p>\n</blockquote>\n<p><strong>Collection fixture for shared Microcks instance (multiple test classes):</strong></p>\n<pre><code>[CollectionDefinition(\"Microcks\")]\npublic class MicrocksCollection : ICollectionFixture&lt;MicrocksFixture&gt; { }\n\npublic class MicrocksFixture : IAsyncLifetime\n{\n    public MicrocksContainer Container { get; private set; } = null!;\n\n    public async Task InitializeAsync()\n    {\n        Container = new MicrocksBuilder()\n            .WithMainArtifacts(\n                \"contracts/eligibility-check-api.yaml\",\n                \"contracts/eligibility-check-api.apiexamples.yaml\")\n            .Build();\n        await Container.StartAsync();\n    }\n\n    public async Task DisposeAsync() =&gt; await Container.DisposeAsync();\n}\n</code></pre>\n<hr>\n<h2>4. Contract Verification (provider-side conformance)</h2>\n<p>Use <code>TestEndpointAsync</code> with the <code>OPEN_API_SCHEMA</code> runner to assert your running\nimplementation satisfies the contract. Microcks calls IN to your service, so the\nservice must listen on a real TCP port (boot real Kestrel — a <code>WebApplicationFactory</code>\nexposes none). The concrete .NET wiring lives in\n<code>contract-testing-dotnet</code>.</p>\n<pre><code>var request = new TestRequest\n{\n    ServiceId = \"Eligibility Check API:1.0.0\",   // \"info.title:info.version\"\n    RunnerType = TestRunnerType.OPEN_API_SCHEMA,\n    TestEndpoint = $\"http://host.testcontainers.internal:{port}\",\n    Timeout = TimeSpan.FromSeconds(5),\n};\n\nTestResult result = await microcks.TestEndpointAsync(request);\nAssert.True(result.Success);   // do not suppress a failing TestResult\n</code></pre>\n<p><strong>TestResult properties:</strong></p>\n<ul>\n<li><code>result.Success</code> → <code>bool</code> — true only when every replayed example passed.</li>\n<li><code>result.TestCaseResults</code> → per-operation detail for diagnosing a failure.</li>\n</ul>\n<p><strong>What \"verified\" means:</strong> every example in <code>.apiexamples.yaml</code> was replayed\nagainst your running service; all response codes, headers, and body fields matched.</p>\n<blockquote>\n<p>Do NOT use <code>VerifyAsync(name, version)</code> for conformance — it returns a <code>bool</code>\nthat checks how many times a MOCK endpoint was invoked (a consumer-side\nassertion), not whether the provider matches the contract.</p>\n</blockquote>\n<p><strong>CI gate rule:</strong> call <code>TestEndpointAsync</code> in a dedicated test and fail the build\nif <code>result.Success == false</code>. Do not suppress failures.</p>\n<hr>\n<h2>5. AsyncAPI Contracts (Kafka / RabbitMQ)</h2>\n<p>Write AsyncAPI 2.6.0 contracts. Store at <code>.copilot-tracking/skraft-plans/{projectSlug}/details/{date}/contracts/{event-name}-events.yaml</code>.</p>\n<p><strong>Required structure:</strong></p>\n<pre><code>asyncapi: 2.6.0\ninfo:\n  title: {Event API Title}\n  version: 1.0.0\nchannels:\n  {topic-or-queue-name}:\n    subscribe:\n      operationId: on{EventName}\n      message:\n        $ref: \"#/components/messages/{EventName}\"\n    publish:\n      operationId: publish{EventName}\n      message:\n        $ref: \"#/components/messages/{EventName}\"\ncomponents:\n  messages:\n    {EventName}:\n      name: {EventName}\n      payload:\n        type: object\n        required: [eventId, occurredAt]\n        properties:\n          eventId:\n            type: string\n            format: uuid\n          occurredAt:\n            type: string\n            format: date-time\n</code></pre>\n<p><strong>Kafka bindings:</strong></p>\n<pre><code>channels:\n  eligibility.checked:\n    bindings:\n      kafka:\n        groupId: eligibility-consumer-group\n        clientId: eligibility-checker\n</code></pre>\n<p><strong>Consumer test pattern:</strong> subscribe to topic → publish test message via Microcks → assert message received by consumer.</p>\n<p><strong>Producer test pattern:</strong> trigger use case → assert event published on topic via Microcks verification.</p>\n<hr>\n<h2>6. Artifact Bridging</h2>\n<p>Artifacts flow from DESIGN → DISTILL → DELIVER following this convention:</p>\n<table>\n<thead>\n<tr>\n<th>Phase</th>\n<th>Artifact</th>\n<th>Path</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>DESIGN</td>\n<td>OpenAPI contract</td>\n<td><code>.copilot-tracking/skraft-plans/{projectSlug}/details/{date}/contracts/{name}.yaml</code></td>\n</tr>\n<tr>\n<td>DESIGN</td>\n<td>AsyncAPI contract</td>\n<td><code>.copilot-tracking/skraft-plans/{projectSlug}/details/{date}/contracts/{name}-events.yaml</code></td>\n</tr>\n<tr>\n<td>DISTILL</td>\n<td>Microcks examples</td>\n<td><code>.copilot-tracking/skraft-plans/{projectSlug}/details/{date}/contracts/{name}.apiexamples.yaml</code></td>\n</tr>\n<tr>\n<td>DISTILL</td>\n<td>Microcks metadata</td>\n<td><code>.copilot-tracking/skraft-plans/{projectSlug}/details/{date}/contracts/{name}.apimetadata.yaml</code></td>\n</tr>\n<tr>\n<td>DELIVER</td>\n<td>Test imports</td>\n<td>Via <code>MicrocksBuilder.WithMainArtifacts(...)</code> referencing DISTILL artifacts</td>\n</tr>\n</tbody>\n</table>\n<p><strong>Import order for <code>WithMainArtifacts</code>:</strong> pass the OpenAPI/AsyncAPI contract first (schema), then the <code>.apiexamples.yaml</code> (examples), then the <code>.apimetadata.yaml</code> (dispatcher config) — all in a single call.</p>\n<p><strong>Version bump protocol:</strong></p>\n<ol>\n<li>Update <code>info.version</code> in the contract YAML.</li>\n<li>Update <code>metadata.name</code> in both DISTILL artifacts to match (<code>{info.title} - {info.version}</code>).</li>\n<li>Update the <code>ServiceId = \"{title}:{version}\"</code> in <code>TestEndpointAsync</code> calls.</li>\n<li>Commit all three changes atomically.</li>\n</ol>\n<hr>\n<h2>7. Multi-service Testing</h2>\n<p>Use <code>MicrocksContainerEnsemble</code> when the service under test calls multiple downstream APIs.</p>\n<pre><code>var network = new NetworkBuilder().Build();\nvar ensemble = new MicrocksContainerEnsemble(network, \"quay.io/microcks/microcks-uber:1.14.0-native\")\n    .WithMainArtifacts(\n        \"contracts/eligibility-check-api.apiexamples.yaml\",\n        \"contracts/driver-profile-api.apiexamples.yaml\");\nawait ensemble.StartAsync();\n\nUri eligibilityMockUrl = ensemble.MicrocksContainer.GetRestMockEndpoint(\"Eligibility Check API\", \"1.0.0\");\nUri driverMockUrl = ensemble.MicrocksContainer.GetRestMockEndpoint(\"Driver Profile API\", \"1.0.0\");\n</code></pre>\n<p><strong>Docker Compose variant:</strong> supply a <code>docker-compose.yaml</code> with dependent services and pass it to the ensemble builder for full integration environment startup.</p>\n<hr>\n<h2>8. References</h2>\n<ul>\n<li><a href=\"references/microcks-testcontainers-setup.md\">references/microcks-testcontainers-setup.md</a> — Full .NET setup, MicrocksBuilder API, collection fixtures</li>\n<li><a href=\"references/openapi-samples-authoring.md\">references/openapi-samples-authoring.md</a> — <code>.apiexamples.yaml</code> full spec, all dispatcher types, templating</li>\n<li><a href=\"references/asyncapi-contract-workflow.md\">references/asyncapi-contract-workflow.md</a> — AsyncAPI 2.6.0 snippets, Kafka/RabbitMQ bindings, consumer/producer tests</li>\n<li><a href=\"references/contract-verification.md\">references/contract-verification.md</a> — <code>TestEndpointAsync()</code> patterns, <code>TestResult</code>, CI gate integration</li>\n<li><a href=\"references/dispatchers-reference.md\">references/dispatchers-reference.md</a> — JSON_BODY, JS, Groovy dispatcher full reference</li>\n<li><a href=\"references/artifact-bridging.md\">references/artifact-bridging.md</a> — Convention table, naming rules, version bump protocol</li>\n</ul>\n<p><strong>Examples:</strong></p>\n<ul>\n<li><a href=\"examples/01-openapi-json-body.md\">examples/01-openapi-json-body.md</a> — GET eligibility, JSON_BODY dispatcher, 200/404</li>\n<li><a href=\"examples/02-openapi-js-dispatcher.md\">examples/02-openapi-js-dispatcher.md</a> — POST eligibility, JS dispatcher, age-based routing</li>\n<li><a href=\"examples/03-testcontainers-dotnet.md\">examples/03-testcontainers-dotnet.md</a> — Complete xUnit test class with WebApplicationFactory</li>\n<li><a href=\"examples/04-asyncapi-kafka.md\">examples/04-asyncapi-kafka.md</a> — EligibilityChecked event, consumer + producer tests</li>\n</ul>\n","files":[{"path":"examples/01-openapi-json-body.md","sizeBytes":6020,"isText":true},{"path":"examples/02-openapi-js-dispatcher.md","sizeBytes":8674,"isText":true},{"path":"examples/03-testcontainers-dotnet.md","sizeBytes":10105,"isText":true},{"path":"examples/04-asyncapi-kafka.md","sizeBytes":11846,"isText":true},{"path":"references/artifact-bridging.md","sizeBytes":6772,"isText":true},{"path":"references/asyncapi-contract-workflow.md","sizeBytes":7987,"isText":true},{"path":"references/contract-verification.md","sizeBytes":7349,"isText":true},{"path":"references/dispatchers-reference.md","sizeBytes":6264,"isText":true},{"path":"references/microcks-testcontainers-setup.md","sizeBytes":7707,"isText":true},{"path":"references/openapi-samples-authoring.md","sizeBytes":6765,"isText":true},{"path":"SKILL.md","sizeBytes":15759,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-11-29T00:43:52.626828Z","sha256":"2765B9D26F1EA42EEDBAC5A426D23A27A29EFCD424C2A057ACF003B0D0BFDC7F","sizeBytes":32094},"review":null,"source":{"repositoryUrl":"https://github.com/SebastienDegodez/skraft-plugin","path":"plugins/skraft-framework/skills/contract-testing","license":"GPL-3.0","commit":"c6117c6236a25490bf1916b131866069740c9b22","subtreeSha":"003D045E7EE2534C726D604CD9A39AB1F253261B7206DFE450F8B800C134DDEE","lastSyncedAt":"2026-11-29T00:42:27.348488Z"},"reviewedAt":"2026-11-29T00:46:56.003331Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/SebastienDegodez/skraft-plugin/tree/main/plugins/skraft-framework/skills/contract-testing"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install sebastiendegodez-skraft-plugin@llmmart"},{"target":"git","command":"git clone https://github.com/SebastienDegodez/skraft-plugin.git"}]}