Testland
Browse all skills & agents

wiremock-stubs

Authors WireMock stub mappings for HTTP service mocking - `stubFor` with verb/path/header matchers + `willReturn` response shaping, lifecycle via `WireMockServer` (start / stop) or JUnit `WireMockExtension`, request verification via `verify()`, and dynamic-port allocation for parallel tests. Also carries the Mountebank multi-protocol workflow (TCP / SMTP / LDAP / gRPC imposters, record-playback proxying) in references/mountebank.md. Use when the project is JVM-based and tests need to mock HTTP dependencies (third-party APIs, internal microservices) at the network layer, or when mocking must go beyond HTTP.

Install with skills.sh (any agent)

npx skills add testland/qa --skill wiremock-stubs
View source

wiremock-stubs

Overview

This skill covers the JVM Java API for WireMock stub-mapping authoring and request verification (wiremock-quickstart (opens in new window)). WireMock also has standalone JAR + Docker modes for non-JVM consumers - the matching skill for JS / TS is msw-handlers.

When to use

  • The project is JVM-based (Java / Kotlin / Scala) and tests need to mock HTTP dependencies.
  • Integration tests must run without the real upstream (third-party API rate limits, billing, flaky network).
  • The team needs request recording - WireMock records actual upstream calls during a "proxy mode" run, then replays them.
  • Parallel test execution requires per-test ports - WireMock's dynamic-port mode handles this.

Install

Maven

<dependency>
  <groupId>org.wiremock</groupId>
  <artifactId>wiremock</artifactId>
  <version>${wiremock.version}</version>
  <scope>test</scope>
</dependency>

(Per wiremock-quickstart (opens in new window); pin ${wiremock.version} to the team's chosen 3.x release.)

Gradle

testImplementation 'org.wiremock:wiremock:3.x'   // pin to the chosen release

Authoring stubs

JUnit 4 with @Rule

Per wiremock-quickstart (opens in new window):

import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.junit.Rule;

public class MyServiceTest {

    @Rule
    public WireMockRule wireMockRule = new WireMockRule(8089);

    @Test
    public void example() {
        stubFor(post("/my/resource")
            .withHeader("Content-Type", containing("xml"))
            .willReturn(ok()
                .withHeader("Content-Type", "text/xml")
                .withBody("<response>SUCCESS</response>")));

        // ... test the SUT against http://localhost:8089
    }
}

JUnit 5 with @WireMockTest

For JUnit 5, use @WireMockTest (or WireMockExtension for finer control):

import com.github.tomakehurst.wiremock.junit5.WireMockTest;
import org.junit.jupiter.api.Test;

@WireMockTest(httpPort = 8089)
class MyServiceTest {

    @Test
    void example() {
        stubFor(get("/orders/42")
            .willReturn(jsonResponse(
                "{\"order_id\": 42, \"status\": \"shipped\"}", 200)));

        // exercise SUT against http://localhost:8089/orders/42
    }
}

Pair @WireMockTest with dynamic-port allocation (wireMockConfig().dynamicPort()) for parallel tests, then read the assigned port via WireMockRuntimeInfo.

Stub matching, response shaping, and scenarios

The request-matcher DSL (get / urlPathMatching / withHeader / withQueryParam / matchingJsonPath / withCookie, first-match-wins), the response builders (ok() / okJson() / withFixedDelay / withChunkedDribbleDelay), and stateful scenario stubs are cataloged in references/matchers-and-scenarios.md.

Request verification

After exercising the SUT, assert on requests received:

verify(postRequestedFor(urlEqualTo("/orders"))
    .withRequestBody(matchingJsonPath("$.sku", equalTo("SKU-1"))));

verify(exactly(1), getRequestedFor(urlPathEqualTo("/health")));

verify() throws on mismatch - fails the test with a clear explanation of expected vs. actual requests.

CI integration

# .github/workflows/integration.yml (excerpt)
- name: Run integration tests
  run: mvn -B verify   # WireMock starts in-process per @WireMockTest annotation

- name: Upload WireMock logs
  if: failure()
  uses: actions/upload-artifact@v4
  with:
    name: wiremock-logs
    path: |
      target/wiremock-*.log
      target/surefire-reports/
    retention-days: 14

WireMock writes to JUL by default; route to your project's logger to capture stub-match misses (a common cause of "test passed locally, failed on CI" puzzles).

Anti-patterns

Anti-patternWhy it failsFix
Hard-coded port 8089 across many test classesPort collisions in parallel test execution.Use wireMockConfig().dynamicPort(); read the assigned port from runtime info.
Stubs that match everything (get(anyUrl()))Hides bugs - your SUT calls a wrong URL and the test still passes.Match on specific paths; use verify() to assert exact URLs.
Skipping verify() after exercising the SUTThe test passes if the SUT skips the call entirely (broken control flow).Always verify() the expected request was made.
Standalone WireMock as a separate process in CIRace conditions on startup; harder to debug.Prefer in-process WireMock via @WireMockTest; standalone only when you must mock from outside the JVM.
Recording from productionCaptures real PII; hard to scrub.Record from staging only; if from prod, post-process to strip PII.

Limitations

  • JVM-focused. Standalone mode works from any language but loses the type-safety of the Java DSL.
  • In-memory state only. Scenario state resets when the WireMock server restarts; persistent state requires the standalone mode + on-disk file storage.
  • HTTP-only. No WebSocket / gRPC - for those, use Mountebank per references/mountebank.md.

References

  • wiremock-quickstart (opens in new window) - install, JUnit 4 / 5 setup, stub-mapping DSL, dynamic ports, request matching.
  • WireMock Docs - https://wiremock.org/docs/
  • msw-handlers - JS / TS counterpart (for browser + Node).
  • references/mountebank.md - Mountebank multi-protocol workflow (HTTP + TCP + SMTP + gRPC, record-playback).

Stub matching, response shaping, and stateful scenarios

View source (opens in new window)

Stub matching, response shaping, and stateful scenarios

Stub matching

The stubFor DSL composes a request-matcher chain:

MatcherPurpose
get("/path") / post("/path") / etc.HTTP verb + path matcher.
urlPathMatching("/users/[0-9]+")Regex on path.
withHeader("Content-Type", containing("json"))Header value matcher.
withQueryParam("status", equalTo("active"))Query parameter matcher.
withRequestBody(matchingJsonPath("$.amount", greaterThan(0)))JSON-path body matcher.
withCookie("session", equalTo("abc"))Cookie matcher.

Stubs are first-match-wins by default; the most specific stub should be registered first.

Response shaping

stubFor(get("/orders/42")
    .willReturn(aResponse()
        .withStatus(200)
        .withHeader("Content-Type", "application/json")
        .withBody("{\"order_id\": 42}")
        .withFixedDelay(500)               // simulate latency
        // OR
        .withChunkedDribbleDelay(5, 1000)  // simulate slow chunked transfer
    ));

Common helper response builders:

HelperEffect
ok()200 OK with empty body.
okJson("...")200 + Content-Type: application/json + body.
notFound(), badRequest(), serverError()404 / 400 / 500.
temporaryRedirect("/new")307 + Location.

Stateful stubs (scenarios)

For workflows that depend on prior state (e.g. "first call returns empty cart, second call returns populated cart"):

stubFor(get("/cart")
    .inScenario("Add to cart")
    .whenScenarioStateIs(STARTED)
    .willReturn(okJson("[]")));

stubFor(post("/cart/add")
    .inScenario("Add to cart")
    .whenScenarioStateIs(STARTED)
    .willSetStateTo("Added")
    .willReturn(ok()));

stubFor(get("/cart")
    .inScenario("Add to cart")
    .whenScenarioStateIs("Added")
    .willReturn(okJson("[{\"sku\":\"SKU-1\"}]")));

Mountebank - multi-protocol mock servers

View source (opens in new window)

Mountebank - multi-protocol mock servers

Reference detail for wiremock-stubs (opens in new window). WireMock and MSW are HTTP-only; Mountebank covers the multi-protocol long tail. Author imposters (mock servers) by POSTing JSON definitions to the control API on port 2525.

Per mountebank-readme (opens in new window), supported protocols include: HTTP / HTTPS, TCP (text and binary), SMTP, LDAP, gRPC, WebSockets, GraphQL, SNMP, Telnet / SSH, and NETCONF.

Docs-domain note (verified 2026-05-04): the canonical mbtest.org domain was hijacked (redirects to an unrelated site), so this reference cites the GitHub repo bbyars/mountebank (opens in new window); mbtest.dev is the project's alternate docs domain. Verify both URLs before linking from authored content.

When to use

  • The project mocks non-HTTP protocols (TCP, SMTP, LDAP, gRPC).
  • The team wants record-playback proxying - Mountebank can proxy to a real upstream during recording, then replay the captured responses in subsequent test runs.
  • The team needs JavaScript injection for dynamic response computation per request.

If the team is HTTP-only on the JVM, WireMock (the parent skill) is the lighter fit. For Node / browser HTTP-only, use msw-handlers. Mountebank's strength is multi-protocol breadth; pay the operational cost (a separate process, port 2525) only when you need it.

How to use

  1. Start Mountebank (mb start or the Docker image); the control API listens on port 2525.
  2. POST a JSON imposter to /imposters with a port, a protocol, and one or more stubs.
  3. Give each stub predicates (path / method / header / body matchers) and responses (the reply to send).
  4. Verify: GET http://localhost:2525/imposters/<port> and assert HTTP 200 with your stubs listed before pointing tests at it. If it 404s or the stub is missing, the POST body was malformed - fix the JSON and re-POST.
  5. Point the system under test at the imposter's port and run the tests.
  6. For an unrecorded upstream, use a proxyOnce proxy response to capture real traffic, then replay offline.
  7. DELETE /imposters/<port> in teardown (or restart Mountebank) so stale stubs don't leak between runs.

Install

npm install -g @mbtest/mountebank

(Per mountebank-readme (opens in new window).)

For Docker-based CI (preferred for runner cleanliness):

docker run --rm -p 2525:2525 -p 4545:4545 bbyars/mountebank:latest start

The control API listens on port 2525; imposter ports (4545 in the example) are configured per imposter.

Authoring imposters

Mountebank's data model uses these layers:

LayerPurpose
ImposterOne mock server bound to a port and protocol.
StubA request matcher attached to an imposter - the response triggered when matched.
PredicateA condition on the incoming request (path, method, header, body, JSON path).
ResponseThe reply Mountebank sends when a stub's predicates match.

Create an HTTP imposter

POST to the control API:

curl -X POST http://localhost:2525/imposters \
  -H 'Content-Type: application/json' \
  -d '{
    "port": 4545,
    "protocol": "http",
    "stubs": [{
      "predicates": [{
        "and": [
          { "equals": { "method": "GET", "path": "/orders/42" } }
        ]
      }],
      "responses": [{
        "is": {
          "statusCode": 200,
          "headers": { "Content-Type": "application/json" },
          "body": "{\"order_id\": 42, \"status\": \"shipped\"}"
        }
      }]
    }]
  }'

After this POST, GET http://localhost:4545/orders/42 returns the stubbed response.

Predicate operators

OperatorMeaning
equalsExact match.
deepEqualsDeep equality on a nested object (e.g. JSON body).
containsSubstring / partial match.
startsWith / endsWithAffix matchers.
matchesRegex match.
existsWhether a field is present.
not / or / andBoolean combinators.
injectCustom JavaScript predicate.

Multi-stub responses (cycle through)

If a stub has multiple responses, Mountebank cycles through them in order on subsequent matching requests:

{
  "stubs": [{
    "predicates": [{ "equals": { "method": "GET", "path": "/poll" } }],
    "responses": [
      { "is": { "statusCode": 202 } },
      { "is": { "statusCode": 202 } },
      { "is": { "statusCode": 200, "body": "DONE" } }
    ]
  }]
}

Three calls: 202, 202, 200, then it cycles back. Useful for modeling polling endpoints.

Proxying for record-playback

Set up an imposter as a proxy to a real upstream:

{
  "port": 4545,
  "protocol": "http",
  "stubs": [{
    "predicates": [{ "matches": { "path": ".*" } }],
    "responses": [{
      "proxy": {
        "to": "https://real-upstream.example.com",
        "mode": "proxyOnce"
      }
    }]
  }]
}
ModeBehavior
proxyOnceFirst request hits upstream; response is stored as a stub; subsequent identical requests replay.
proxyAlwaysEvery request hits upstream; every response is stored.
proxyTransparentPass-through; nothing recorded.

proxyOnce is the canonical record-playback workflow - run tests once against a real upstream to populate the imposter, then run forever offline. Each distinct request hits the upstream and Mountebank stores the response as a stub; on every later run the stored stubs answer and the real API is never called.

Test framework integration

For Node.js test suites, use the mountebank npm package programmatically:

import mb from 'mountebank';

const mbServer = await mb.create({ port: 2525, allowInjection: true });

// POST imposter via fetch / axios / the mb client lib
await fetch('http://localhost:2525/imposters', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ port: 4545, protocol: 'http', stubs: [...] }),
});

// Run tests against http://localhost:4545

// Tear down
await fetch('http://localhost:2525/imposters/4545', { method: 'DELETE' });
await mbServer.close();

CI integration

# .github/workflows/integration.yml
- name: Start Mountebank
  run: |
    npx -p @mbtest/mountebank mb start &
    npx wait-on http://localhost:2525

- name: Seed imposters
  run: bash scripts/seed-mountebank.sh

- run: npm test

- name: Stop Mountebank
  if: always()
  run: pkill -f 'mountebank' || true

For a more robust pattern, run Mountebank in Docker as a sidecar service rather than a background process - kills + cleanup are cleaner.

Anti-patterns

Anti-patternWhy it failsFix
Hard-coded imposter ports across many testsPort collisions under parallel CI execution.Use dynamic ports; capture them from the control API's response.
Predicates with regex that match unintended pathsTest passes because the wrong stub responded.Anchor regexes (^/$); prefer equals over matches when possible.
allowInjection: true in production-adjacent envsJS injection is powerful; allows arbitrary code execution.Only enable for local / CI; never on a shared mock server.
Forgetting to delete imposters between test runsStale imposters persist across runs; tests interfere.DELETE /imposters/<port> in test teardown OR restart Mountebank.
Recording in proxyAlways mode and committing the capturesCaptures may include real PII / tokens.Use proxyOnce; review captured stubs before committing; scrub PII via JSON Schema or jq pre-commit.

Limitations

  • Operational overhead. A separate process / container per CI run; harder to set up than in-process WireMock or MSW.
  • JSON-heavy authoring. Imposter definitions are JSON-by-API; there's no fluent DSL like WireMock's stubFor.
  • Documentation domain reliability. See the docs-domain note at the top: cite the GitHub README and mbtest.dev.

References

  • mountebank-readme (opens in new window) - main repo: install, supported protocols, key features.
  • mbtest.dev - alternate documentation domain (verify before linking).
  • msw-handlers - HTTP-only alternative for browser + Node.

Related skills

boundary-value-generator

Generates boundary-value test cases from typed input specifications - for each input field, produces the canonical 6-point set (one below, at, and above the lower bound; one below, at, and above the upper bound) plus equivalence-class representatives. Emits cases as parameterized test inputs (pytest @parametrize / Jest test.each / xUnit InlineData / etc.). Use when a function or endpoint has numeric / string-length / collection-size constraints and the team needs systematic edge-case coverage.

faker-data

Fixes test data that breaks tests - factory values in a shape the code under test rejects (a phone number that is not E.164), fixtures that only pass when the whole suite runs in order, and random values that make an assertion pass or fail depending on the run. Authors test-data factories with Faker: the Python `faker` library, the `@faker-js/faker` JS port, and the `faker-ruby` gem - install per language, the provider catalogue (person / internet / location / date / finance / lorem), locale selection and multi-locale mode, and seed-based determinism for reproducible runs. Scope is generating fresh values for tests that start from nothing, not replacing values inside a dataset that already holds real records - that goes to pii-masking-pipeline-builder. Use when fixtures need realistic values, a stable shape, or a fixed seed.

golden-file-conventions

Reference catalog for snapshot / golden file management - naming conventions, directory layout, when to add / update / remove a baseline, sanitization (timestamps, IDs, PII), per-OS / per-runtime variant strategy, and review workflow for snapshot diffs in PRs. Use when designing a snapshot-testing convention or auditing an existing one for drift.

malicious-payload-bank

Reference catalog of curated adversarial input payloads keyed by attack class - SQL injection, XSS, SSRF, path traversal, command injection, XXE, prototype pollution, regex DoS, Unicode confusables, header injection - plus per-context guidance for which payloads apply (URL parameter / form input / JSON body / file upload). Use when authoring negative-test cases for input validation, fuzz targets, or a security-focused test suite that needs to exercise the OWASP Top 10 attack surface.

msw-handlers

Authors Mock Service Worker (MSW) request handlers for both browser and Node.js test environments using the `http.get` / `http.post` / `HttpResponse.json` API, wires them via `setupWorker` (browser) or `setupServer` (Node), and manages the test lifecycle (`server.listen` / `resetHandlers` / `close`). Use when the project uses JavaScript / TypeScript and needs to mock fetch / XHR at the network layer for both Vitest / Jest unit tests and Cypress / Playwright integration tests.

negative-test-generator

Covers the refusal paths a handler already implements but nothing tests - a batch endpoint that must apply all rows or none, optimistic-concurrency version conflicts between two editors, or a delete that deliberately separates who you are from what you may do from the state the record is in. For each happy-path test, produces companions exercising input validation rejection, missing required fields, type mismatches, authorization failures, rate-limit errors, and adversarial payloads from the malicious-payload-bank, emitted as parameterized tests in the project's runner format. Use when code has deliberate error paths and the suite only proves the success case.

pairwise-test-case-generator

Generates parameterized test inputs combining boundary-value, equivalence-class, and pairwise-combinatorial cases from a typed multi-input specification - produces the cross-product of cases up to a configurable strength (1-wise / 2-wise / N-wise) using all-pairs reduction so the test surface stays tractable. Emits cases in the project's test-runner-native parametrize format. Use when a function or endpoint takes 3+ inputs whose interactions matter and full Cartesian product would explode.

seed-data-curator

Builds a reproducible E2E seed dataset for the project's test environments - picks a representative user / org / data-product cross-section, generates the rows via the project's chosen factory library (FactoryBot / mimesis / Bogus / Faker + factory_boy), persists the dataset as a checked-in fixture (SQL dump / JSON / per-engine seed file), and wires it into the test bootstrap. Use when starting E2E coverage on a project that has no seed strategy, or when an existing seed has drifted.

synthetic-data-toolkit

Umbrella for the synthetic test data generators beyond plain Faker - FactoryBot (Ruby factories with traits, associations, and build / create / build_stubbed strategies), Mimesis (fast type-hinted Python generator with the Schema/Field bulk pattern and 46 locales), and Bogus (.NET typed `Faker<T>` builders with `.RuleFor` / `StrictMode` / `UseSeed`). Picks the right generator by language and job, shows side-by-side equivalents of the same fixture across all four ecosystems, and carries each tool's full workflow in references/ (factory-bot.md, mimesis.md, bogus.md). faker-data stays the default for plain field values in Python / JS / Ruby; use this skill when the project needs typed factory orchestration, .NET fixtures, or a documented "which tool should I use" decision.

synthetic-pii-generator

Generates realistic-but-fake personally identifiable information (PII) - emails, phone numbers, SSNs / national IDs, addresses, names, credit-card numbers (test BIN ranges), date-of-birth - for non-production environments. Wraps Faker / mimesis with PII-aware constraints so generated values match real format expectations (Luhn-valid card numbers, region-valid phone formats, ITIN/SSN format) without ever generating real-person data. Use when seeding test environments, building demo data, or replacing real PII in copied datasets.

test-data-patterns

Pure reference catalog of the cross-language object-construction patterns for test data - Test Data Builder (Pryce/Freeman), Factory (with traits and associations), Object Mother, Fixture composition (per-test / per-describe / shared), Snapshot (defers to `golden-file-conventions` for the operational details), and Production-Data Anonymisation. Distinct from the per-language tool skills (`faker-data` and the `synthetic-data-toolkit` umbrella covering FactoryBot / mimesis / Bogus) which document tool-specific configuration; this catalog is the architecture-tier reference for choosing **which pattern** before reaching for the tool. Use when choosing a test-data construction pattern for a new suite, or auditing an existing suite whose fixtures have drifted into shared mutable state.