Runnable Examples

The examples/ directory is a single home for self-contained, runnable MockServer examples across every language and interface. Examples are grouped by language or interface at the top level, with two cross-cutting topic folders (chaos/, wasm/) that apply regardless of client.

Every example follows the same shape: one runnable entry point (script / program) and a short README.md with What it demonstrates · Prerequisites · Run · Expected output.

Quick start

Most examples assume a running MockServer on localhost:1080:

docker run -d --rm -p 1080:1080 mockserver/mockserver

curl/, json/, and chaos/ scripts honour a MOCKSERVER_URL environment variable (e.g. export MOCKSERVER_URL=http://localhost:1080). Each language-track README explains how to install the corresponding client.

 

Examples by Language / Interface

Language / Interface What it covers
curl/ Raw REST control-plane examples as runnable curl shell scripts — the most comprehensive reference, covering every API endpoint
json/ Expectation and initialiser JSON payloads, usable directly with curl -d @file.json or any HTTP client
java/ Java client and proxy examples — a buildable, CI-tested Maven module covering mocking scenarios and proxy usage with multiple HTTP libraries
node/ Node.js / TypeScript client examples including callbacks, LLM mocking, MCP mocking, OpenAPI expectations, and request retrieval
python/ Python client examples covering response actions, forward actions, request matchers, OpenAPI expectations, verification, and LLM/MCP mocking
ruby/ Ruby client examples covering response actions, forward actions, request matchers, OpenAPI expectations, verification, and proxying
go/ Go client examples including expectation creation and interactive breakpoints to modify proxied responses in-flight
dotnet/ .NET / C# client examples including expectation creation and interactive breakpoints to modify proxied responses in-flight
rust/ Rust client examples including expectation creation and interactive breakpoints to modify proxied responses in-flight
php/ PHP client examples (REST only) covering expectation creation and static forward overrides — no WebSocket breakpoints
postman/ A ready-to-import Postman collection covering the MockServer control-plane REST API — published with each release
bruno/ A Bruno API collection covering the full control-plane REST API (expectations, verify, scenario, contract, pact, chaos, SLO, OIDC, SAML, SCIM, and more) — published with each release
docker-compose/ Deployment scenarios including mock-from-OpenAPI, record-replay proxy, validation proxy, chaos proxy, mTLS, persistence, and expectation initialiser
kubernetes/ Kubernetes deployments on local k3s (k3d) — incl. load-injection metrics visualised in Grafana over Prometheus and OpenTelemetry
chaos/ Fault injection across HTTP, TCP, gRPC, and LLM layers via runnable curl scripts — MockServer's flagship differentiator
wasm/ Custom WASM body-matcher rules in Rust (prebuilt) and Go, plus the mockserver-wasm-sdk for typed request-envelope matching
 

Feature Categories (curl/ and json/)

The curl/ and json/ directories are the most comprehensive reference: they cover every MockServer API endpoint and are organised into feature-category subdirectories. The same categories exist in both trees (shell scripts and raw JSON payloads respectively). Per-language stateful scenario examples live under examples/<language>/scenario/ for every client (curl, json, java, node, python, ruby, go, dotnet, rust, php).

Category What it covers
create_expectation/ Basic expectation creation, arrays of expectations, hit-count limits, TTL expiry, and update by ID
matchers/ Request matching by path, method, query parameters, headers, cookies, and body (regex, XML, JSON, JSON Schema, JsonPath, XPath, fuzzy)
response_action/ Canned HTTP responses: status codes, headers, cookies, delays, weighted responses, switch-on-hit-count, generate from JSON Schema
forward_action/ Forward requests to upstream hosts over HTTP/HTTPS with request and response overrides
forward_fallback/ Forward with fallback response when upstream returns an error or times out
template_response/ Generate responses from JavaScript or Velocity templates
template_forward/ Forward requests using JavaScript or Velocity templates
error_action/ Error actions: drop connection, return random bytes
callback/ Java class callback actions
forward_class_callback/ Forward requests using a Java class callback
verify/ Verify recorded requests by count (exact, at-least, at-most), sequence, OpenAPI operation, and response
retrieve/ Retrieve recorded requests, request-response pairs, log messages, and active or recorded expectations
clear/ Clear expectations and logs selectively by request matcher, OpenAPI operation, expectation ID, or logs only
reset/ Reset MockServer (clear all state)
openapi/ Create expectations from an OpenAPI spec URL, by operation, or from the classpath
contract/ Run an OpenAPI spec as a contract test against a live service
pact/ Import a Pact v3 contract with provider state and activate the state so it matches
scenario/ Stateful scenarios — state-machine flows (scenarioName / scenarioState / newScenarioState), sequential/cycling responses (responseMode), timed & externally-triggered transitions, and cross-protocol correlation
graphql/ Import a GraphQL SDL and match requests by GraphQL query AST body matcher
grpc_stream/ Mock gRPC server-streaming responses and gRPC error statuses
websocket/ WebSocket expectations with subprotocol and message matchers
sse/ Server-Sent Events response with multiple events
binary_response/ Return raw binary data (base64-encoded) in a response
dns_response/ DNS A record and NXDOMAIN mock responses
llm/ Mock OpenAI-style chat completions, embeddings, and rerank responses
mcp/ Mock an MCP server tool (tools/list and tools/call) over JSON-RPC
a2a/ Serve an A2A agent card and return completed A2A tasks (Agent-to-Agent protocol)
 

Chaos Engineering Scenarios

The chaos/ directory demonstrates MockServer's multi-layer fault injection — spanning TCP, HTTP, gRPC, and LLM protocols.

Scenario Layer What it demonstrates
http_latency_gaussian HTTP Inject Gaussian-distributed latency on a mocked response
http_error_with_retry_after HTTP Deterministic 503 error injection with a Retry-After header
connection_drop_seeded HTTP Probabilistic TCP connection drops with a fixed seed for reproducibility
gradual_degradation_ramp HTTP Error probability that ramps from 0% to 100% over a configurable duration
outage_window_controllable_clock HTTP Time-based outage window using the controllable clock (PUT /mockserver/clock)
named_quota_rate_limit HTTP Fixed-window rate limiting with a named, shared quota counter
service_scoped_profile_with_live_patch HTTP Register a service-level chaos profile and live-patch it with PATCH
tcp_reset_peer TCP Inject TCP RST (reset) on connections to a target host
tcp_bandwidth_throttle TCP Throttle bandwidth to a target host at the TCP layer
grpc_status_chaos gRPC Inject gRPC error statuses with latency and custom trailers
llm_midstream_truncation LLM Truncate an LLM streaming (SSE) response mid-stream
 

Docker Compose Recipes

The docker-compose/ directory contains quick-start recipes and configuration permutations. Each recipe is exercised in CI.

Recipe What it does
mock-from-openapi Serve mocks generated from a mounted OpenAPI spec
record-replay-proxy Proxy to an upstream and record traffic to a replayable file
validation-proxy Proxy to an upstream and validate requests/responses against an OpenAPI spec
chaos-proxy Proxy to an upstream while injecting latency and intermittent errors
docker_compose_with_mtls Serve mocks over mutual TLS (mTLS) with a mounted CA and client-certificate verification
docker_compose_with_persisted_expectations Persist expectations to a mounted file so they survive container restarts
docker_compose_with_expectation_initialiser Load expectations from a mounted initialiser JSON file at container startup

The docker-compose/ directory also contains several server_port_* and forward / remote-host configuration permutations (port set by command, by short / long environment-variable name, from a custom or default properties file, and forward-with-override) — browse the folder for the full set.

 

Kubernetes — Load Injection Metrics in Grafana

The kubernetes/ examples run on a local k3s cluster (via k3d), so they need only Docker — no cloud cluster.

Example What it covers
load-injection-observability A one-command stack — MockServer, Prometheus, an OpenTelemetry Collector, and Grafana — that drives a load scenario and renders every load-injection metric on a provisioned Grafana dashboard: active VUs, throughput and request rates, p50/p90/p95/p99 latency, failures and status codes, throttling, data transfer, plus JVM heap/GC/threads and real pod CPU & memory. The same metrics are exposed over both Prometheus and OpenTelemetry (OTLP), so you can chart the injector alongside your system under test on one dashboard.

This is the fastest way to see the Observability & Metrics section of the Load Injection guide in action — ./run.sh creates the cluster, triggers the run, and opens Grafana on localhost:3000.

 

Next Steps / See Also

  • Getting Started — start MockServer, set up your first expectation, and verify requests step by step.
  • MockServer Clients — control MockServer from Java, JavaScript, Python, Ruby, Go, .NET, Rust, PHP, or the REST API.