### Getting Started with Stubr in Rust
Source: https://wiremock.org/docs/solutions/rust
Demonstrates how to start a Stubr mock server using a WireMock JSON stub file and make assertions on the response using the asserhttp crate. It shows how to obtain the server's URI and perform HTTP requests.
```rust
use asserhttp::*
#[tokio::test]
async fn getting_started() {
// run a mock server with the stub 👇
let stubr = stubr::Stubr::start("tests/stubs/hello.json").await;
// or use 'start_blocking' for a non-async version
// the mock server started on a random port e.g. '127.0.0.1:43125'
// so we use the stub instance 'path' (or 'uri') method to get the address back
let uri = stubr.path("/hello");
reqwest::get(uri).await
// (optional) use asserhttp for assertions
.expect_status_ok()
.expect_content_type_text()
.expect_body_text_eq("Hello stubr");
}
```
--------------------------------
### WireMock Library Usage with Pact API
Source: https://wiremock.org/docs/solutions/pact
Demonstrates setting up WireMock as a library in a Java test. It includes starting the server, stubbing requests, and integrating with WireMockPactApi for contract management. This example covers the lifecycle from setup to saving pacts.
```java
public class ExampleTest {
private static WireMockServer server;
private static WireMockPactApi wireMockPactApi;
@BeforeAll
public static void beforeEach() throws IOException {
server = new WireMockServer();
server.start();
stubFor(
post(anyUrl())
.willReturn(
ok()
.withHeader("content-type", "application/json")
.withBody("{\"a\":\"b\"}"))
.withMetadata(
new Metadata(
Map.of(
WireMockPactMetadata.METADATA_ATTR,
new WireMockPactMetadata()
.setProvider("some-specific-provider")))));
wireMockPactApi =
WireMockPactApi.create(
new WireMockPactConfig()
.setConsumerDefaultValue("my-service")
.setProviderDefaultValue("unknown-service")
.setPactJsonFolder("the/pact-json/folder"));
wireMockPactApi.clearAllSaved();
}
@Test
public void testInvoke() {
// Do stuff that invokes WireMock...
}
@AfterAll
public static void after() {
for (final ServeEvent serveEvent : server.getAllServeEvents()) {
wireMockPactApi.addServeEvent(serveEvent);
}
// Save pact-json to folder given in WireMockPactApi
wireMockPactApi.saveAll();
server.stop();
}
}
```
--------------------------------
### WireMock Scenario Setup Example
Source: https://wiremock.org/docs/stateful-behaviour
Demonstrates setting up a stateful scenario in WireMock using Java and its JSON configuration. This allows testing complex client-server interactions that depend on sequential states.
```Java
@Test
public void toDoListScenario() {
stubFor(get(urlEqualTo("/todo/items")).inScenario("To do list")
.whenScenarioStateIs(STARTED)
.willReturn(aResponse()
.withBody("" +
" - Buy milk
" +
"")));
stubFor(post(urlEqualTo("/todo/items")).inScenario("To do list")
.whenScenarioStateIs(STARTED)
.withRequestBody(containing("Cancel newspaper subscription"))
.willReturn(aResponse().withStatus(201))
.willSetStateTo("Cancel newspaper item added"));
stubFor(get(urlEqualTo("/todo/items")).inScenario("To do list")
.whenScenarioStateIs("Cancel newspaper item added")
.willReturn(aResponse()
.withBody("" +
" - Buy milk
" +
" - Cancel newspaper subscription
" +
"")));
WireMockResponse response = testClient.get("/todo/items");
assertThat(response.content(), containsString("Buy milk"));
assertThat(response.content(), not(containsString("Cancel newspaper subscription")));
response = testClient.postWithBody("/todo/items", "Cancel newspaper subscription", "text/plain", "UTF-8");
assertThat(response.statusCode(), is(201));
response = testClient.get("/todo/items");
assertThat(response.content(), containsString("Buy milk"));
assertThat(response.content(), containsString("Cancel newspaper subscription"));
}
```
```JSON
{
"mappings": [
{
"scenarioName": "To do list",
"requiredScenarioState": "Started",
"request": {
"method": "GET",
"url": "/todo/items"
},
"response": {
"status": 200,
"body": "- Buy milk
"
}
},
{
"scenarioName": "To do list",
"requiredScenarioState": "Started",
"newScenarioState": "Cancel newspaper item added",
"request": {
"method": "POST",
"url": "/todo/items",
"bodyPatterns": [
{ "contains": "Cancel newspaper subscription" }
]
},
"response": {
"status": 201
}
},
{
"scenarioName": "To do list",
"requiredScenarioState": "Cancel newspaper item added",
"request": {
"method": "GET",
"url": "/todo/items"
},
"response": {
"status": 200,
"body": "- Buy milk
- Cancel newspaper subscription
"
}
}
]
}
```
--------------------------------
### Wiremock-rs: MockServer Setup and Request Mocking in Rust
Source: https://wiremock.org/docs/solutions/rust
Demonstrates how to start a WireMock-rs mock server, define a mock for a GET request on '/hello' with a 200 OK response, and verify the response using the surf HTTP client. This snippet requires the 'wiremock', 'async-std', and 'surf' crates.
```Rust
use wiremock::{MockServer, Mock, ResponseTemplate};
use wiremock::matchers::{method, path};
#[async_std::main]
async fn main() {
// Start a background HTTP server on a random local port
let mock_server = MockServer::start().await;
// Arrange the behaviour of the MockServer adding a Mock:
// when it receives a GET request on '/hello' it will respond with a 200.
Mock::given(method("GET")).and(path("/hello"))
.respond_with(ResponseTemplate::new(200))
.mount(&mock_server).await;
// Verify the response
let status = surf::get(format!("{}/hello", &mock_server.uri()))
.await.unwrap().status();
assert_eq!(status.as_u16(), 200);
}
```
--------------------------------
### WireMock Testcontainers Example (Golang)
Source: https://wiremock.org/docs/solutions/testcontainers
This Golang example illustrates using WireMock with Testcontainers for testing. It starts a WireMock container, specifies a mapping file, and performs an HTTP GET request to validate the server's response. It relies on the `wiremock-testcontainers-go` library.
```go
package testcontainers_wiremock_quickstart
import (
"context"
"testing"
. "github.com/wiremock/wiremock-testcontainers-go"
)
func TestWireMock(t *testing.T) {
ctx := context.Background()
mappingFileName := "hello-world.json"
container, err := RunContainerAndStopOnCleanup(ctx, t,
WithMappingFile(mappingFileName),
)
if err != nil {
t.Fatal(err)
}
statusCode, out, err := SendHttpGet(container, "/hello", nil)
if err != nil {
t.Fatal(err, "Failed to get a response")
}
// Verify the response
if statusCode != 200 {
t.Fatalf("expected HTTP-200 but got %d", statusCode)
}
if string(out) != "Hello, world!" {
t.Fatalf("expected 'Hello, world!' but got %s", out)
}
}
```
--------------------------------
### WireMock Recording Quick Start
Source: https://wiremock.org/docs/record-playback
Demonstrates the basic steps to record API interactions using WireMock's web UI and command-line tools. It covers starting WireMock, accessing the recorder UI, making a request, and stopping the recording to generate stub mappings.
```shell
$ curl http://localhost:8080/recordables/123
```
```shell
$ curl http://localhost:8080/recordables/123
{
"message": "Congratulations on your first recording!"
}
```
--------------------------------
### Start and Stop WireMockServer in Java
Source: https://wiremock.org/docs/java-usage
Demonstrates programmatic creation, starting, and stopping of a WireMockServer instance. This is useful when not using JUnit rules or other WireMock lifecycle managers. It requires importing `WireMockServer` and `options`.
```Java
WireMockServer wireMockServer = new WireMockServer(options().port(8089)); //No-args constructor will start on port 8080, no HTTPS
wireMockServer.start();
// Sometime later
wireMockServer.stop();
```
--------------------------------
### Configure Static WireMock Client with Imports
Source: https://wiremock.org/docs/java-usage
Illustrates configuring the static WireMock client, including necessary static imports for DSL methods like `get`. This setup allows for fluent stubbing and verification directly.
```Java
import static com.github.tomakehurst.wiremock.client.WireMock.*;
configureFor("wiremock.host", 8089);
stubFor(get(....));
```
--------------------------------
### Run WireMock Standalone JAR
Source: https://wiremock.org/docs/download-and-installation
Executes the WireMock standalone JAR file from the command line. This starts a WireMock server with all necessary dependencies included.
```bash
java -jar wiremock-standalone-3.13.1.jar
```
--------------------------------
### Start WireMock Docker Container (CLI Args)
Source: https://wiremock.org/docs/standalone/docker
Launches a WireMock Docker container and passes custom command-line arguments. This example configures HTTPS on port 8443 and enables verbose logging, mirroring the standalone JAR's options.
```docker
docker run -it --rm \
-p 8443:8443 \
--name wiremock \
wiremock/wiremock:3.13.1 \
--https-port 8443 --verbose
```
--------------------------------
### Go WireMock Client Stubbing Example
Source: https://wiremock.org/docs/solutions/golang
Illustrates how to use the Go WireMock client library to stub API resources. This example shows creating a client, defining a POST stub with query parameters, and returning a JSON response with a specific status code and headers.
```go
import (
"net/http"
"testing"
"github.com/wiremock/go-wiremock"
)
func TestSome(t *testing.T) {
wiremockClient := wiremock.NewClient("http://0.0.0.0:8080")
defer wiremockClient.Reset()
wiremockClient.StubFor(
wiremock.Post(wiremock.URLPathEqualTo("/user")).
WithQueryParam("name", wiremock.EqualTo("John Doe")),
).WillReturnResponse(
wiremock.NewResponse().
WithJSONBody(map[string]interface{}{
"code": 400,
"detail": "detail",
}).
WithHeader("Content-Type", "application/json").
WithStatus(http.StatusBadRequest),
)
}
```
--------------------------------
### WireMock Java Recording API
Source: https://wiremock.org/docs/record-playback
Provides examples of how to programmatically start and stop WireMock recording using its Java API. It covers both the static DSL and client instance approaches for managing recording sessions.
```java
// Static DSL
WireMock.startRecording("http://examples.wiremockapi.cloud/");
List recordedMappings = WireMock.stopRecording();
// Client instance
WireMock wireMockClient = new WireMock(8080);
wireMockClient.startStubRecording("http://examples.wiremockapi.cloud/");
List recordedMappings = wireMockClient.stopStubRecording();
// Directly
WireMockServer wireMockServer = new WireMockServer();
wireMockServer.start();
wireMockServer.startRecording("http://examples.wiremockapi.cloud/");
List recordedMappings = wireMockServer.stopRecording();
```
--------------------------------
### Start WireMock Docker Container (Env Var Args)
Source: https://wiremock.org/docs/standalone/docker
Starts a WireMock Docker container by passing command-line arguments via the WIREMOCK_OPTIONS environment variable. This method is supported from version 3.2.0-2 and allows for cleaner container definitions.
```docker
docker run -it --rm \
-e WIREMOCK_OPTIONS='--https-port 8443 --verbose' \
-p 8443:8443 \
--name wiremock \
wiremock/wiremock:3.13.1
```
--------------------------------
### Java WireMockServer Browser Proxying Example
Source: https://wiremock.org/docs/multi-domain-mocking
Demonstrates setting up a WireMockServer with browser proxying enabled, configuring an HttpClient to use system properties for proxy settings, and defining stubs for different hostnames. This example shows how to target specific domains by setting host properties and restoring previous proxy configurations.
```Java
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import com.github.tomakehurst.wiremock.common.JvmProxyConfigurer;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
public class WireMockBrowserProxyingTest {
public void testViaProxyUsingServer() throws Exception {
WireMockServer wireMockServer = new WireMockServer(WireMockConfiguration.options()
.dynamicPort()
.enableBrowserProxying(true)
);
wireMockServer.start();
// Configure WireMock to use the dynamic port
WireMock.configureFor("localhost", wireMockServer.port());
HttpClient httpClient = HttpClientBuilder.create()
.useSystemProperties() // This must be enabled for auto proxy config
.build();
// Configure JVM proxy settings to point to WireMockServer
JvmProxyConfigurer.configureFor(wireMockServer);
// Stub for the first domain
wireMockServer.stubFor(get("/things")
.withHost(equalTo("my.first.domain"))
.willReturn(ok("Domain 1")));
// Stub for the second domain
wireMockServer.stubFor(get("/things")
.withHost(equalTo("my.second.domain"))
.willReturn(ok("Domain 2")));
// Make a request to the first domain
HttpResponse response = httpClient.execute(new HttpGet("http://my.first.domain/things"));
String responseBody = EntityUtils.toString(response.getEntity()); // Should == Domain 1
System.out.println("Response for my.first.domain: " + responseBody);
// Make a request to the second domain
response = httpClient.execute(new HttpGet("http://my.second.domain/things"));
responseBody = EntityUtils.toString(response.getEntity()); // Should == Domain 2
System.out.println("Response for my.second.domain: " + responseBody);
wireMockServer.stop();
// Restore previous JVM proxy settings
JvmProxyConfigurer.restorePrevious();
}
public static void main(String[] args) {
WireMockBrowserProxyingTest test = new WireMockBrowserProxyingTest();
try {
test.testViaProxyUsingServer();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
--------------------------------
### Run WireMock Standalone JAR
Source: https://wiremock.org/docs/standalone/java-jar
Executes the WireMock standalone JAR file to start the server. This is the primary method for running WireMock in its own process. Ensure you have Java installed and the JAR file downloaded.
```bash
$ java -jar wiremock-standalone-3.13.1.jar
```
--------------------------------
### Standalone Setup: Compile Proto Files
Source: https://wiremock.org/docs/grpc
Command to compile Protocol Buffer files into a descriptor set file. This file is used by the WireMock gRPC extension to understand the gRPC service definitions.
```Shell
protoc --descriptor_set_out wiremock/grpc/services.dsc ExampleServices.proto
```
--------------------------------
### Standalone Setup: Create WireMock Data Directories
Source: https://wiremock.org/docs/grpc
Command to create the necessary directory structure for WireMock's standalone gRPC extension. This includes directories for stub mappings and gRPC descriptor files.
```Shell
mkdir -p wiremock wiremock/mappings wiremock/grpc
```
--------------------------------
### Standalone Setup: Run WireMock with gRPC Extension
Source: https://wiremock.org/docs/grpc
Command to run the WireMock standalone JAR with the gRPC extension. It specifies the classpath to include the necessary JARs and sets the root directory for WireMock data.
```Shell
java -cp wiremock-standalone-.jar:wiremock-grpc-extension-standalone-.jar \
wiremock.Run \
--root-dir wiremock
```
--------------------------------
### Docker Compose for WireMock Service
Source: https://wiremock.org/docs/standalone/docker
Configure a WireMock service using Docker Compose. This example defines the service, specifies the WireMock image, sets a container name, and overrides the entrypoint to pass startup arguments.
```yaml
version: "3"
services:
wiremock:
image: "wiremock/wiremock:latest"
container_name: my_wiremock
entrypoint: ["/docker-entrypoint.sh", "--global-response-templating", "--disable-gzip", "--verbose"]
```
--------------------------------
### Run WireMock Docker Container
Source: https://wiremock.org/docs/download-and-installation
Starts a WireMock container using Docker, mapping the default WireMock port (8080) to the host. This provides an isolated and easily deployable WireMock instance.
```bash
docker run -it --rm \
-p 8080:8080 \
--name wiremock \
wiremock/wiremock:3.13.1
```
--------------------------------
### Math Operations
Source: https://wiremock.org/docs/response-templating
Provides examples of the 'math' helper for performing basic arithmetic operations including addition, subtraction, multiplication, division, and modulo. The helper always returns a number.
```Handlebars
{{math 1 '+' 2}}
```
```Handlebars
{{math 4 '-' 2}}
```
```Handlebars
{{math 2 '*' 3}}
```
```Handlebars
{{math 8 '/' 2}}
```
```Handlebars
{{math 10 '%' 3}}
```
--------------------------------
### WireMock Spring Boot Integration Setup
Source: https://wiremock.org/docs/solutions/spring-boot-integration
The official WireMock Spring Boot integration library simplifies configuring WireMock with Spring Boot and JUnit 5. It offers declarative setup, supports multiple WireMockServer instances, and automatically manages Spring environment properties without adding unnecessary beans.
```Java
import org.springframework.boot.test.context.SpringBootTest;
import com.github.tomakehurst.wiremock.WireMockServer;
import org.junit.jupiter.api.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WireMockSpringIntegrationTest {
@Test
public void testWireMockServer() {
// Assuming WireMockServer is configured via properties or auto-configuration
// Example of stubbing a request:
WireMockServer wireMockServer = new WireMockServer(); // Or get from context if managed
wireMockServer.start();
wireMockServer.stubFor(get(urlEqualTo("/api/users"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"id\": 1, \"name\": \"Test User\"}")));
// ... make HTTP call to the running WireMockServer and assert response ...
wireMockServer.stop();
}
}
```
```Groovy
import org.springframework.boot.test.context.SpringBootTest
import com.github.tomakehurst.wiremock.WireMockServer
import org.junit.jupiter.api.Test
import static com.github.tomakehurst.wiremock.client.WireMock.*
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class WireMockSpringIntegrationTest {
@Test
void testWireMockServer() {
// Assuming WireMockServer is configured via properties or auto-configuration
// Example of stubbing a request:
def wireMockServer = new WireMockServer()
wireMockServer.start()
wireMockServer.stubFor(get(urlEqualTo('/api/users'))
.willReturn(aResponse()
.withStatus(200)
.withHeader('Content-Type', 'application/json')
.withBody('{"id": 1, "name": "Test User"}')))
// ... make HTTP call to the running WireMockServer and assert response ...
wireMockServer.stop()
}
}
```
--------------------------------
### Initialize WireMock Container and Add Mapping (C)
Source: https://wiremock.org/docs/solutions/c_cpp
Demonstrates the initialization of a default WireMock container and the process of adding a mapping file to it. It also shows how to upload a file to the container's filesystem and handle potential errors during container startup.
```c
#include
#include
#include "testcontainers-c-wiremock.h"
int main() {
printf("Creating new container: %s\n", DEFAULT_WIREMOCK_IMAGE);
int requestId = tc_wm_new_default_container();
tc_wm_with_mapping(requestId, "test_data/hello.json", "hello");
tc_with_file(requestId, "test_data/hello.json", "/home/wiremock/mappings/hello2.json");
struct tc_run_container_return ret = tc_run_container(requestId);
int containerId = ret.r0;
if (!ret.r1) {
printf("Failed to run the container: %s\n", ret.r2);
if (containerId != -1) { // Print container log
char* log = tc_get_container_log(containerId);
if (log != NULL) {
printf("\n%s\n", log);
}
}
return -1;
}
// ...
return 0;
}
```
--------------------------------
### WireMock JUnit Rule Setup
Source: https://wiremock.org/docs/quickstart/java-junit
Demonstrates how to add the WireMock JUnit rule to a test class. This rule automatically manages the WireMock server's lifecycle, starting and stopping it for each test case.
```java
import static com.github.tomakehurst.wiremock.client.WireMock.*;
// ...
@Rule
public WireMockRule wireMockRule = new WireMockRule(8089); // No-args constructor defaults to port 8080
```
--------------------------------
### Basic WireMockRule Usage
Source: https://wiremock.org/docs/junit-extensions
Demonstrates the basic setup of WireMockRule for JUnit 4, which automatically manages the WireMock server lifecycle. The rule starts the server on the default port (8080) before each test and stops it afterwards.
```java
@Rule
public WireMockRule wireMockRule = new WireMockRule();
```
--------------------------------
### Create WireMock Client Instance
Source: https://wiremock.org/docs/java-usage
Explains how to create instances of the `WireMock` client, which is useful for interacting with multiple WireMock server instances simultaneously. The constructor accepts host, port, and an optional context path.
```Java
WireMock wireMock = new WireMock("some.host", 9090, "/wm"); // As above, 3rd param is for non-root servlet deployments
wireMock.register(get(....)); // Equivalent to stubFor()
```
--------------------------------
### WireMock Pytest Fixture with Testcontainers (Python)
Source: https://wiremock.org/docs/solutions/testcontainers
This Python example shows how to integrate WireMock with Pytest using Testcontainers. It defines a session-scoped fixture that starts a WireMock container, configures a mapping, and makes it available for tests. It uses the `wiremock-testcontainers` library.
```python
import pytest
from wiremock.testing.testcontainer import wiremock_container
@pytest.fixture(scope="session") # (1)
def wm_server():
with wiremock_container(secure=False) as wm:
Config.base_url = wm.get_url("__admin") # (2)=
Mappings.create_mapping(
Mapping(
request=MappingRequest(method=HttpMethods.GET, url="/hello"),
response=MappingResponse(status=200, body="hello"),
persistent=False,
)
) # (3)
yield wm
def test_get_hello_world(wm_server): # (4)
resp1 = requests.get(wm_server.get_url("/hello"), verify=False)
assert resp1.status_code == 200
assert resp1.content == b"hello"
```
--------------------------------
### Using GET_OR_HEAD HTTP Method in WireMock Java DSL
Source: https://wiremock.org/docs/stubbing
Shows how to use the special `GET_OR_HEAD` HTTP method in WireMock's Java DSL to match incoming requests for both GET and HEAD operations. The example includes a test assertion to verify the stub's behavior.
```Java
@Test
public void getOrHeadDemo() {
stubFor(getOrHead(urlEqualTo("/get-or-head-test"))
.willReturn(okJson("{\"key\": \"value\"}")));
assertThat(testClient.get("/get-or-head-test").statusCode(), is(200));
}
```
--------------------------------
### Programmatic WireMock Extension Setup
Source: https://wiremock.org/docs/junit-jupiter
Demonstrates setting up multiple WireMock instances programmatically using JUnit Jupiter's `@RegisterExtension`. It shows how to configure ports, add extensions like `ResponseTemplateTransformer`, and access runtime information. This approach provides full control over WireMock configuration and lifecycle.
```Java
public class ProgrammaticWireMockTest {
@RegisterExtension
static WireMockExtension wm1 = WireMockExtension.newInstance()
.options(wireMockConfig().dynamicPort().dynamicHttpsPort())
.build();
@RegisterExtension
static WireMockExtension wm2 = WireMockExtension.newInstance()
.options(wireMockConfig()
.dynamicPort()
.extensions(new ResponseTemplateTransformer(
getTemplateEngine(),
options.getResponseTemplatingGlobal(),
getFiles(),
templateModelProviders
)
)
.build();
@Test
void test_something_with_wiremock() {
// You can get ports, base URL etc. via WireMockRuntimeInfo
WireMockRuntimeInfo wm1RuntimeInfo = wm1.getRuntimeInfo();
int httpsPort = wm1RuntimeInfo.getHttpsPort();
// or directly via the extension field
int httpPort = wm1.port();
// You can use the DSL directly from the extension field
wm1.stubFor(get("/api-1-thing").willReturn(ok()));
wm2.stubFor(get("/api-2-stuff").willReturn(ok()));
}
}
```
--------------------------------
### Running Multiple WireMock Instances with Spring Boot
Source: https://wiremock.org/docs/spring-boot
This example demonstrates how to configure multiple WireMock server instances using the `@EnableWireMock` annotation in a Spring Boot application. Each instance can be named and associated with specific properties for its base URL and port, enabling distinct mocking setups for different services.
```java
@SpringBootTest(classes = WireMockSpringExtensionTest.AppConfiguration.class)
@EnableWireMock({
@ConfigureWireMock(
name = "user-service",
baseUrlProperties = "user-service.url",
portProperties = "user-service.port"
),
@ConfigureWireMock(
name = "todo-service",
baseUrlProperties = "todo-service.url",
portProperties = "todo-service.port"
)
})
public class WireMockSpringExtensionTest {
@SpringBootApplication
static class AppConfiguration {}
@InjectWireMock("user-service")
private WireMockServer mockUserService;
@InjectWireMock("todo-service")
private WireMockServer mockTodoService;
}
```
--------------------------------
### Start WireMock Docker Container (Default)
Source: https://wiremock.org/docs/standalone/docker
Starts a single WireMock container with default configuration. It maps port 8080 from the host to the container and names the container 'wiremock'. Access the admin interface at http://localhost:8080/__admin/mappings.
```docker
docker run -it --rm \
-p 8080:8080 \
--name wiremock \
wiremock/wiremock:3.13.1
```
--------------------------------
### Stubbing Basic GET Requests with WireMock Java DSL
Source: https://wiremock.org/docs/stubbing
Demonstrates the simplest way to stub a GET request to a specific URL using WireMock's Java DSL, returning a 200 OK status.
```Java
stubFor(get("/some/thing")
.willReturn(aResponse().withStatus(200)));
```
--------------------------------
### WireMock Testcontainers for Go Example
Source: https://wiremock.org/docs/solutions/golang
Demonstrates using the WireMock Testcontainers module for Go to run WireMock single-shot containers within Golang tests. It shows how to initialize a container with a mapping file and send HTTP requests to the mocked API.
```go
import (
"context"
. "github.com/wiremock/wiremock-testcontainers-go"
"testing"
)
func TestWireMock(t *testing.T) {
// Create Container
ctx := context.Background()
container, err := RunContainerAndStopOnCleanup(ctx,
WithMappingFile("hello", "hello-world.json"),
)
if err != nil {
t.Fatal(err)
}
// Send the HTTP GET request to the mocked API
statusCode, out, err := SendHttpGet(container, "/hello", nil)
if err != nil {
t.Fatal(err, "Failed to get a response")
}
// Verify the response
if statusCode != 200 {
t.Fatalf("expected HTTP-200 but got %d", statusCode)
}
if string(out) != "Hello, world!" {
t.Fatalf("expected 'Hello, world!' but got %v", string(out))
}
}
```
--------------------------------
### Example API Mocking Test Case
Source: https://wiremock.org/docs/quickstart/java-junit
An example JUnit test case that uses WireMock to stub a POST request to '/my/resource' with an XML content type. It then sends a request using Java 11+'s HttpClient and verifies the response status and body using AssertJ.
```java
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.junit.Rule;
import org.junit.Test;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.assertj.core.api.Assertions.assertThat;
public class ApiMockingTest {
@Rule
public WireMockRule wiremockServer = new WireMockRule(8089);
@Test
public void exampleTest() {
// Setup the WireMock mapping stub for the test
stubFor(post("/my/resource")
.withHeader("Content-Type", containing("xml"))
.willReturn(ok()
.withHeader("Content-Type", "text/xml")
.withBody("SUCCESS")));
// Setup HTTP POST request (with HTTP Client embedded in Java 11+)
final HttpClient client = HttpClient.newBuilder().build();
final HttpRequest request = HttpRequest.newBuilder()
.uri(wiremockServer.url("/my/resource"))
.header("Content-Type", "text/xml")
.POST().build();
// Send the request and receive the response
final HttpResponse response =
client.send(request, HttpResponse.BodyHandlers.ofString());
// Verify the response (with AssertJ)
assertThat(response.statusCode()).as("Wrong response status code").isEqualTo(200);
assertThat(response.body()).as("Wrong response body").contains("SUCCESS");
}
}
```
--------------------------------
### Run WireMock Standalone JAR
Source: https://wiremock.org/docs/mock-api-templates/usage
Instructions for running WireMock standalone JAR with API templates. Requires placing the JSON file in a 'mappings' directory next to the JAR.
```bash
java -jar wiremock-jre8-standalone-3.13.1.jar
```
--------------------------------
### WireMock Standalone JAR Download Link
Source: https://wiremock.org/docs/download-and-installation
Provides the direct download URL for the WireMock standalone JAR file. This JAR can be used to run WireMock as a separate process.
```url
https://repo1.maven.org/maven2/org/wiremock/wiremock-standalone/4.0.0-beta.10/wiremock-standalone-4.0.0-beta.10.jar
```
--------------------------------
### Initialize WireMockServer with gRPC Extension
Source: https://wiremock.org/docs/grpc
Configure and initialize the WireMockServer with the gRPC extension enabled and specify the root directory containing gRPC descriptor files.
```Java
WireMockServer wm = new WireMockServer(wireMockConfig()
.dynamicPort()
.withRootDirectory("src/test/resources/wiremock")
.extensions(new GrpcExtensionFactory())
));
```
--------------------------------
### Get Single Stub Mapping by ID (HTTP API)
Source: https://wiremock.org/docs/stubbing
Provides the HTTP API endpoint for retrieving a single stub mapping by its ID.
```APIDOC
GET http://:/__admin/mappings/{id}
Description:
Retrieves a specific stub mapping by its UUID.
Parameters:
{id}: The UUID of the stub mapping to retrieve.
```
--------------------------------
### Initialize WireMockGrpcService
Source: https://wiremock.org/docs/grpc
Create an instance of `WireMockGrpcService` to interact with the gRPC service mocking functionality, providing the WireMock server port and service name.
```Java
WireMockGrpcService mockGreetingService =
new WireMockGrpcService(
new WireMock(wm.getPort()),
"com.example.grpc.GreetingService"
);
```
--------------------------------
### Get Local Hostname with hostname Helper
Source: https://wiremock.org/docs/response-templating
The `hostname` helper prints the hostname of the local machine where WireMock is running. This can be useful for logging or dynamic configuration.
```wiremock-templating
{{hostname}}
```
--------------------------------
### Dockerfile for Custom WireMock Image
Source: https://wiremock.org/docs/standalone/docker
Build a custom Docker image for WireMock by extending the official image. This example shows how to copy custom WireMock configurations into the container and override the default entrypoint script to pass specific startup arguments.
```dockerfile
FROM wiremock/wiremock:latest
COPY wiremock /home/wiremock
ENTRYPOINT ["/docker-entrypoint.sh", "--global-response-templating", "--disable-gzip", "--verbose"]
```
--------------------------------
### Publishing WireMock Pacts to Pact Broker via Shell Script
Source: https://wiremock.org/docs/solutions/pact
Provides a shell script example for publishing WireMock pacts to a Pact broker. It demonstrates how to determine the participant version number using git and a versioning tool, and then uses a publishing script with authentication details.
```shell
current_version=$(npx git-changelog-command-line \
--patch-version-pattern "^fix.*" \
--print-current-version)
git_hash=`git rev-parse --short HEAD`
participant_version_number="$current_version-$git_hash"
npx pactflow-publish-sh \
--username=dXfltyFMgNOFZAxr8io9wJ37iUpY42M \
--password=O5AIZWxelWbLvqMd8PkAVycBJh2Psyg1 \
--pactflow-broker-url=https://test.pactflow.io/contracts/publish \
--build-url=http://whatever/ \
--pact-json-folder=wiremock-pact-example-springboot-app/src/test/resources/pact-json \
--participant-version-number=$participant_version_number
```
--------------------------------
### WireMock Maven Test Dependency
Source: https://wiremock.org/docs/download-and-installation
Adds the WireMock library to your Maven project for testing purposes. Ensure you use the correct version for your WireMock setup.
```xml
org.wiremock
wiremock
4.0.0-beta.10
test
```
--------------------------------
### Get Single Stub Mapping by ID
Source: https://wiremock.org/docs/stubbing
Illustrates how to retrieve a specific stub mapping by its unique ID using the WireMock Java API and the HTTP API.
```Java
import java.util.UUID;
import static com.github.tomakehurst.wiremock.core.WireMock.getSingleStubMapping;
// Get a single stub mapping by ID
UUID stubId = UUID.randomUUID(); // Replace with actual stub ID
getSingleStubMapping(stubId);
```
--------------------------------
### Run WireMock Docker with Extensions
Source: https://wiremock.org/docs/standalone/docker
Starts a WireMock Docker container and enables custom extensions, such as the Webhooks extension. This involves mounting a directory containing extension JAR files to the container and specifying the extension class via a command-line argument.
```docker
docker run -it --rm \
-p 8080:8080 \
--name wiremock \
-v $PWD/extensions:/var/wiremock/extensions \
wiremock/wiremock \
--extensions org.wiremock.webhooks.Webhooks
```
--------------------------------
### Configure WireMock Logging Notifier
Source: https://wiremock.org/docs/configuration
Sets an alternative notifier for WireMock logging. The default logs to SLF4j. This example uses ConsoleNotifier to log to standard output.
```Java
// Provide an alternative notifier. The default logs to slf4j.
.notifier(new ConsoleNotifier(true))
```
--------------------------------
### Securing WireMock Admin API (Command Line & cURL)
Source: https://wiremock.org/docs/standalone/java-jar
Details how to secure the WireMock Admin API using basic authentication via the command line. It shows how to start WireMock with credentials and how to make authenticated requests using `curl` with the `Authorization` header.
```bash
java -jar wiremock-standalone.jar --admin-api-basic-auth my-username:my-super-secret-password
```
```bash
curl -X GET --location "http://localhost:8080/__admin/requests" \
-H "Authorization: Basic bXktdXNlcm5hbWU6bXktc3VwZXItc2VjcmV0LXBhc3N3b3Jk"
```
--------------------------------
### Proxying HTTPS with curl
Source: https://wiremock.org/docs/proxying
Demonstrates how to proxy HTTPS traffic through WireMock using curl, including an example for forcing HTTP/1.1 for compatibility with older clients or specific server configurations.
```shell
curl --proxy-insecure -x https://localhost:8443 -k 'https://www.example.com/'
curl --http1.1 --proxy-insecure -x https://localhost:8443 -k 'https://www.example.com/'
```
--------------------------------
### Test proxying via Docker
Source: https://wiremock.org/docs/proxying
Provides instructions to run a Docker container for spdyproxy, which can be used as an external HTTPS proxy to test WireMock's proxying capabilities.
```shell
docker run --rm -it -p 44300:44300 wernight/spdyproxy
curl --proxy-insecure -x https://localhost:44300 -k 'https://www.example.com/'
```
--------------------------------
### WireMock Standalone Gradle Dependency
Source: https://wiremock.org/docs/download-and-installation
Includes the WireMock standalone JAR as a test dependency in a Gradle project. This allows for easy inclusion of the complete WireMock distribution in test setups.
```groovy
testImplementation "org.wiremock:wiremock-standalone:3.13.1"
```
--------------------------------
### Number Formatting with Digit Configuration
Source: https://wiremock.org/docs/response-templating
Shows how to bound the number of digits before and after the decimal point using parameters like 'maximumIntegerDigits' and 'minimumFractionDigits' with the numberFormat helper.
```Handlebars
{{{numberFormat 1234.567 maximumIntegerDigits=3 minimumFractionDigits=6}}}
```