WireMock is a comprehensive API mocking and service virtualization library for testing and development environments with HTTP server simulation capabilities.
Comprehensive response generation with support for static content, delays, transformations, fault injection, and proxying capabilities for realistic API simulation and testing scenarios.
Main builder class for creating HTTP response definitions with extensive configuration options.
/**
* Builder for HTTP response definitions
*/
class ResponseDefinitionBuilder {
// Static Factory Methods
/** Create basic response builder */
static ResponseDefinitionBuilder aResponse();
/** Create response builder from existing definition */
static ResponseDefinitionBuilder like(ResponseDefinition responseDefinition);
/** Create JSON response with object serialization */
static ResponseDefinitionBuilder jsonResponse(Object body);
/** Create empty response builder */
static ResponseDefinitionBuilder responseDefinition();
/** Create 200 OK JSON response */
static ResponseDefinitionBuilder okForJson(Object body);
/** Create 200 OK empty JSON response */
static ResponseDefinitionBuilder okForEmptyJson();
// Status and Headers
/** Set HTTP status code */
ResponseDefinitionBuilder withStatus(int status);
/** Set HTTP status message */
ResponseDefinitionBuilder withStatusMessage(String message);
/** Add single response header */
ResponseDefinitionBuilder withHeader(String key, String... values);
/** Set all response headers */
ResponseDefinitionBuilder withHeaders(HttpHeaders headers);
// Response Body
/** Set response body from string */
ResponseDefinitionBuilder withBody(String body);
/** Set response body from byte array */
ResponseDefinitionBuilder withBody(byte[] body);
/** Set JSON response body from JsonNode */
ResponseDefinitionBuilder withJsonBody(JsonNode jsonBody);
/** Set response body from file */
ResponseDefinitionBuilder withBodyFile(String fileName);
/** Set Base64-encoded response body */
ResponseDefinitionBuilder withBase64Body(String base64Body);
// Delays and Performance
/** Set fixed delay before response */
ResponseDefinitionBuilder withFixedDelay(Integer milliseconds);
/** Set random delay with distribution */
ResponseDefinitionBuilder withRandomDelay(DelayDistribution distribution);
/** Set log-normal random delay */
ResponseDefinitionBuilder withLogNormalRandomDelay(double median, double sigma);
/** Set uniform random delay */
ResponseDefinitionBuilder withUniformRandomDelay(int lower, int upper);
/** Set chunked response with dribble delay */
ResponseDefinitionBuilder withChunkedDribbleDelay(int chunks, int totalDuration);
// Response Transformation
/** Add response transformers */
ResponseDefinitionBuilder withTransformers(String... transformerNames);
/** Set transformer parameters */
ResponseDefinitionBuilder withTransformerParameters(Map<String, Object> parameters);
/** Add single transformer with parameter */
ResponseDefinitionBuilder withTransformer(String name, String key, Object value);
// Fault Simulation
/** Inject network fault */
ResponseDefinitionBuilder withFault(Fault fault);
/** Control gzip compression */
ResponseDefinitionBuilder withGzipDisabled(boolean disabled);
// Proxying
/** Proxy request to another server */
ProxyResponseDefinitionBuilder proxiedFrom(String proxyBaseUrl);
}Usage Examples:
// Basic response
stubFor(get(urlEqualTo("/api/health"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"status\": \"healthy\"}")));
// File-based response with delay
stubFor(get(urlEqualTo("/api/users"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBodyFile("users.json")
.withFixedDelay(500)));
// Response with random delay
stubFor(get(urlEqualTo("/api/slow"))
.willReturn(aResponse()
.withStatus(200)
.withUniformRandomDelay(1000, 3000)
.withBody("Slow response")));Static factory methods for common HTTP responses.
/**
* Quick response factory methods in WireMock class
*/
// Success Responses
/** HTTP 200 OK response */
static ResponseDefinitionBuilder ok();
/** HTTP 200 OK with body */
static ResponseDefinitionBuilder ok(String body);
/** HTTP 200 OK JSON response */
static ResponseDefinitionBuilder okJson(String body);
/** HTTP 200 OK XML response */
static ResponseDefinitionBuilder okXml(String body);
/** HTTP 201 Created response */
static ResponseDefinitionBuilder created();
/** HTTP 204 No Content response */
static ResponseDefinitionBuilder noContent();
// Client Error Responses
/** HTTP 400 Bad Request response */
static ResponseDefinitionBuilder badRequest();
/** HTTP 401 Unauthorized response */
static ResponseDefinitionBuilder unauthorized();
/** HTTP 403 Forbidden response */
static ResponseDefinitionBuilder forbidden();
/** HTTP 404 Not Found response */
static ResponseDefinitionBuilder notFound();
// Server Error Responses
/** HTTP 500 Internal Server Error response */
static ResponseDefinitionBuilder serverError();
// Custom Status
/** Custom HTTP status response */
static ResponseDefinitionBuilder status(int status);Usage Examples:
// Quick success responses
stubFor(get(urlEqualTo("/api/status"))
.willReturn(ok("System is running")));
stubFor(post(urlEqualTo("/api/users"))
.willReturn(created()
.withHeader("Location", "/api/users/123")));
// Quick error responses
stubFor(get(urlEqualTo("/api/forbidden"))
.willReturn(forbidden()));
stubFor(get(urlEqualTo("/api/missing"))
.willReturn(notFound()
.withBody("Resource not found")));Extended response builder for proxy configurations with request manipulation.
/**
* Extended response builder for proxy configurations
*/
class ProxyResponseDefinitionBuilder extends ResponseDefinitionBuilder {
/** Add header to proxy request */
ProxyResponseDefinitionBuilder withAdditionalRequestHeader(String key, String value);
/** Remove header from proxy request */
ProxyResponseDefinitionBuilder withRemoveRequestHeader(String key);
/** Remove URL prefix before proxying */
ProxyResponseDefinitionBuilder withProxyUrlPrefixToRemove(String prefix);
}Usage Examples:
// Basic proxying
stubFor(any(anyUrl())
.willReturn(aResponse()
.proxiedFrom("https://api.example.com")));
// Proxy with request modification
stubFor(get(urlMatching("/api/.*"))
.willReturn(aResponse()
.proxiedFrom("https://backend.example.com")
.withAdditionalRequestHeader("X-Forwarded-By", "WireMock")
.withRemoveRequestHeader("X-Internal-Token")
.withProxyUrlPrefixToRemove("/api")));Various delay distribution implementations for realistic response timing simulation.
/**
* Delay distribution interfaces and implementations
*/
interface DelayDistribution {
/** Sample delay value from distribution */
long sampleMillis();
}
class UniformDistribution implements DelayDistribution {
/** Create uniform distribution between min and max */
UniformDistribution(int lower, int upper);
long sampleMillis();
}
class LogNormal implements DelayDistribution {
/** Create log-normal distribution */
LogNormal(double median, double sigma);
long sampleMillis();
}
class ChunkedDribbleDelay {
/** Create chunked delay specification */
ChunkedDribbleDelay(int chunks, int totalDuration);
int getChunks();
int getTotalDuration();
}Usage Examples:
// Custom delay distributions
stubFor(get(urlEqualTo("/api/variable"))
.willReturn(aResponse()
.withRandomDelay(new UniformDistribution(100, 1000))
.withStatus(200)));
stubFor(get(urlEqualTo("/api/realistic"))
.willReturn(aResponse()
.withLogNormalRandomDelay(200.0, 0.1)
.withStatus(200)));
// Chunked response with dribble
stubFor(get(urlEqualTo("/api/stream"))
.willReturn(aResponse()
.withChunkedDribbleDelay(5, 2000)
.withBody("Streaming data...")));Network-level fault simulation for testing error handling and resilience.
/**
* Network fault simulation
*/
enum Fault {
/** Reset connection from peer side */
CONNECTION_RESET_BY_PEER,
/** Send empty response and close connection */
EMPTY_RESPONSE,
/** Send malformed HTTP chunk */
MALFORMED_RESPONSE_CHUNK,
/** Send random data then close connection */
RANDOM_DATA_THEN_CLOSE
}
interface FaultInjector {
/** Inject connection reset by peer */
void connectionResetByPeer();
/** Send empty response and close */
void emptyResponseAndCloseConnection();
/** Send malformed response chunk */
void malformedResponseChunk();
/** Send random data and close */
void randomDataAndCloseConnection();
}Usage Examples:
// Fault injection for resilience testing
stubFor(get(urlEqualTo("/api/unreliable"))
.willReturn(aResponse()
.withFault(Fault.CONNECTION_RESET_BY_PEER)));
stubFor(get(urlEqualTo("/api/corrupt"))
.willReturn(aResponse()
.withFault(Fault.MALFORMED_RESPONSE_CHUNK)));
stubFor(post(urlEqualTo("/api/timeout"))
.willReturn(aResponse()
.withFault(Fault.EMPTY_RESPONSE)));Supporting types for response configuration and metadata.
class ResponseDefinition {
int getStatus();
String getStatusMessage();
byte[] getBody();
String getBodyFileName();
HttpHeaders getHeaders();
Integer getFixedDelayMilliseconds();
DelayDistribution getDelayDistribution();
ChunkedDribbleDelay getChunkedDribbleDelay();
String getProxyBaseUrl();
Fault getFault();
List<String> getTransformers();
Map<String, Object> getTransformerParameters();
boolean wasConfigured();
}
class HttpHeaders {
static HttpHeaders httpHeaders();
HttpHeaders plus(HttpHeader header);
HttpHeaders plus(String key, String... values);
HttpHeader getHeader(String key);
List<HttpHeader> all();
Set<String> keys();
int size();
boolean isEmpty();
}
class HttpHeader {
static HttpHeader httpHeader(String key, String... values);
String key();
String firstValue();
List<String> values();
boolean isPresent();
boolean isSingleValued();
boolean hasValueMatching(StringValuePattern valuePattern);
}
class Meta {
int getTotal();
}Install with Tessl CLI
npx tessl i tessl/maven-org-wiremock--wiremock