### NUnit and NFluent Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/using-wiremock-in-unittests.md A basic example of using WireMock.Net with NUnit and NFluent for testing. It shows how to start and stop the WireMock server, define a mock response, and make an HTTP request to it. ```csharp [SetUp] public void StartMockServer() { _server = WireMockServer.Start(); } [Test] public async Task Should_respond_to_request() { // Arrange (start WireMock.Net server) _server .Given(Request.Create().WithPath("/foo").UsingGet()) .RespondWith( Response.Create() .WithStatusCode(200) .WithBody(@"{ "msg": "Hello world!" }") ); // Act (use a HttpClient which connects to the URL where WireMock.Net is running) var response = await new HttpClient().GetAsync($"{_server.Urls[0]}/foo"); // Assert Check.That(response).IsEqualTo(EXPECTED_RESULT); } [TearDown] public void ShutdownServer() { _server.Stop(); } ``` -------------------------------- ### Start WireMock.Net server Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/wiremock-as-dotnet-tool.md Command to start the WireMock.Net server using the installed tool. ```cmd dotnet-wiremock ``` -------------------------------- ### Install Dependencies Source: https://github.com/wiremock/wiremock.org/blob/main/README.md Installs the project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Start Development Server Source: https://github.com/wiremock/wiremock.org/blob/main/README.md Starts the local development server for the documentation site. ```bash pnpm dev ``` -------------------------------- ### Java DSL for recording Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/record-playback.mdx Examples of starting and stopping recording using WireMock's Java DSL. ```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(); ``` -------------------------------- ### Starting WireMock Server with HTTPS Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/using-https-ssl.md Examples of starting a WireMock server with HTTPS enabled, either by setting a flag or by configuring URLs. ```csharp var server1 = WireMockServer.Start(port: 8443, ssl: true); // or like this var server2 = WireMockServer.Start(new WireMockServerSettings { Urls = new[] { "http://localhost:9091", "https://localhost:9443" } }); ``` -------------------------------- ### Build and Run Example Project Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/development-information.md Instructions for building and running an example .NET Framework 4.8 project. ```bash dotnet build ``` ```bash .\bin\Debug\WireMock.Net.ConsoleApplication.exe ``` -------------------------------- ### Java Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/stateful-behaviour.mdx Example of setting up stateful behaviour using scenarios in Java. ```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")); } ``` -------------------------------- ### wiremock-rs example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/solutions/rust.mdx An example demonstrating how to use the wiremock-rs crate to set up a mock server and make a request. ```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); } ``` -------------------------------- ### Stubr example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/solutions/rust.mdx An example demonstrating how to use the Stubr project, which adapts wiremock-rs to support existing WireMock JSON stubs. ```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"); } ``` -------------------------------- ### Error Message Example 2 Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/xamarin-could-not-load-file-or-assembly.md Example of a file not found error during binding. ```text The operation failed. Bind result: hr = 0x80070002. The system cannot find the file specified. Assembly manager loaded from: C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll Running under executable C:\git\WireMock.Net\examples\WireMock.Net.Console.Net461.Classic\bin\Debug\WireMock.Net.Console.Net461.Classic.exe ``` -------------------------------- ### WireMock Rule Setup Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/quickstart/java-junit.mdx JUnit rule to automatically start and stop WireMock per test case. ```java @Rule public WireMockRule wireMockRule = new WireMockRule(8089); // No-args constructor defaults to port 8080 ``` -------------------------------- ### WebSocket Example Configuration Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/configuration.mdx An example of configuring WireMockServer with specific WebSocket settings. ```java WireMockServer wm = new WireMockServer( wireMockConfig() .port(8080) .webSocketIdleTimeout(600000) // 10 minute idle timeout .webSocketMaxTextMessageSize(2097152) // 2MB max text message .webSocketMaxBinaryMessageSize(5242880)); // 5MB max binary message ``` -------------------------------- ### Example Test Case Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/quickstart/java-junit.mdx A JUnit test case demonstrating WireMock stubbing, request sending, and response verification. ```java import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; ... @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"); } ``` -------------------------------- ### Kotlin WireMock DSL Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/solutions/kotlin.mdx An example demonstrating the Kotlin WireMock library for defining requests and responses. ```kotlin wiremock.get { url equalTo "/users/1" } returns { statusCode = 200 header = "Content-Type" to "application/json" body = """ { "id": 1, "name": "Bob" } """ } ``` -------------------------------- ### With Icon Source: https://github.com/wiremock/wiremock.org/blob/main/src/components/CloudCallout.example.mdx An example of the CloudCallout component with a title, content, and an icon. ```astro Get started with WireMock Cloud for enhanced API mocking capabilities. The icon will be styled with an orange border and background. ``` -------------------------------- ### Assembly Binding Redirect Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/xamarin-could-not-load-file-or-assembly.md Example of assembly binding redirects in app.config. ```xml ``` -------------------------------- ### Basic Usage Source: https://github.com/wiremock/wiremock.org/blob/main/src/components/CloudCallout.example.mdx A basic example of the CloudCallout component with a title and content. ```astro This is a cloud callout with a custom orange background (#ff980080). You can add any content inside the callout. ``` -------------------------------- ### Start with command line arguments Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/standalone/docker.mdx This command starts a WireMock container, maps port 8443, and passes additional command-line arguments like `--https-port 8443` and `--verbose`. ```sh docker run -it --rm \ -p 8443:8443 \ --name wiremock \ wiremock/wiremock:${VERSIONS.WIREMOCK_STABLE} \ --https-port 8443 --verbose ``` -------------------------------- ### Basic stubbing example in JSON Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/stubbing.mdx Configures a GET request to /some/thing to return a 200 status, 'Hello, world!' body, and 'text/plain' Content-Type header. ```json { "request": { "method": "GET", "url": "/some/thing" }, "response": { "status": 200, "body": "Hello, world!", "headers": { "Content-Type": "text/plain" } } } ``` -------------------------------- ### Start a server Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/stubbing.mdx Starts a WireMock server on localhost, choosing an available port automatically. ```csharp var server = WireMockServer.Start(); ``` -------------------------------- ### Golang Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/solutions/testcontainers.mdx Example of using WireMock Testcontainers in Golang. ```golang 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) } } ``` -------------------------------- ### Install WireMock as a .NET tool Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/wiremock-as-dotnet-tool.md Command to install the dotnet-wiremock tool globally. ```cmd dotnet tool install --global dotnet-wiremock ``` -------------------------------- ### Start WireMock as a standalone virtual service Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/solutions/service-virtualization.mdx This command starts the WireMock standalone JAR, configuring it to listen on port 8080 and use a specified directory for storing mock configurations and files. ```bash java -jar wiremock-standalone-3.13.2.jar --port 8080 --root-dir ./service-mocks ``` -------------------------------- ### Kotest Extension for WireMock Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/solutions/kotlin.mdx An example showing how to integrate WireMock with the Kotest testing framework. ```kotlin class SomeTest : FunSpec({ val customerServiceServer = WireMockServer(9000) listener(WireMockListener(customerServiceServer, ListenerMode.PER_SPEC)) test("let me get customer information") { customerServiceServer.stubFor( WireMock.get(WireMock.urlEqualTo("/customers/123")) .willReturn(WireMock.ok()) ) val connection = URL("http://localhost:9000/customers/123").openConnection() as HttpURLConnection connection.responseCode shouldBe 200 } // ------------OTHER TEST BELOW ---------------- }) ``` -------------------------------- ### Groovy DSL Binding Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/solutions/groovy.mdx This example demonstrates how to use the wiremock-groovy library to define WireMock stubs and verify requests in a Groovy environment, similar to Spock syntax. ```groovy @Rule WireMockRule wireMockRule = new WireMockRule() def wireMockStub = new WireMockGroovy() def "example verifying test" () { ... then: 1 == wireMockStub.count { method "GET" url "/some/url" } } def "test using groovy truth if you need at least one request and shows example matcher" () { ... then: wireMockStub.count { method "POST" url "/some/url" headers { "Content-Type" { matches ".*xml" } } } } ``` -------------------------------- ### Configuration Example - Java Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/websockets.mdx Example of configuring WireMockServer with custom WebSocket idle timeout and max text message size. ```java WireMockServer wm = new WireMockServer( wireMockConfig() .port(8080) .webSocketIdleTimeout(600000) // 10 minutes .webSocketMaxTextMessageSize(1048576)); // 1MB ``` -------------------------------- ### C# Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/faults.mdx This C# example demonstrates how to configure a WireMock server to respond with a malformed response chunk with a 50% probability. ```csharp var server = WireMockServer.Start(); server .Given(Request.Create().WithPath("/fault").UsingGet()) .RespondWith(Response.Create() .WithStatusCode(201) .WithHeader("Content-Type", "application/json") .WithBody(@"{ \"result\": 100 }") .WithFault(FaultType.MALFORMED_RESPONSE_CHUNK, 0.5)); ``` -------------------------------- ### WireMock REST Client Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/solutions/nodejs.mdx An example showing how to use the WireMock REST Client to interact with a running WireMock server. ```javascript import { WireMockRestClient } from 'wiremock-rest-client'; const wireMock = new WireMockRestClient('http://localhost:8080'); const stubMappings = await wireMock.mappings.getAllMappings(); console.log(stubMappings); await wireMock.global.shutdown(); ``` -------------------------------- ### Error Message Example 1 Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/xamarin-could-not-load-file-or-assembly.md Example of the 'System.Memory' assembly load error. ```text WireMock.Exceptions.WireMockException : Service start failed with error: One or more errors occurred. (Could not load type of field 'Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketTransportOptions:k__BackingField' (1) due to: Could not load file or assembly 'System.Memory, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies.) ----> System.AggregateException : One or more errors occurred. (Could not load type of field 'Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketTransportOptions:k__BackingField' (1) due to: Could not load file or assembly 'System.Memory, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies.) ----> System.TypeLoadException : Could not load type of field 'Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketTransportOptions:k__BackingField' (1) due to: Could not load file or assembly 'System.Memory, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. TearDown : System.NullReferenceException : Object reference not set to an instance of an object ``` -------------------------------- ### Get Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/wiremock-java-compatibility.md An example of a Wiremock Java mapping for a GET request. ```json { "id" : "ef53ea56-f118-4b3a-8c69-a9484851d99a", "name" : "weatherforecast", "request" : { "url" : "/WeatherForecast", "method" : "GET" }, "response" : { "status" : 200, "body" : "[{\"date\":\"2021-09-09T20:44:48.0992639-03:00\",\"temperatureC\":51,\"temperatureF\":123,\"summary\":\"Hot\"},{\"date\":\"2021-09-10T20:44:48.0992692-03:00\",\"temperatureC\":34,\"temperatureF\":93,\"summary\":\"Mild\"},{\"date\":\"2021-09-11T20:44:48.0992696-03:00\",\"temperatureC\":43,\"temperatureF\":109,\"summary\":\"Sweltering\"},{\"date\":\"2021-09-12T20:44:48.0992698-03:00\",\"temperatureC\":46,\"temperatureF\":114,\"summary\":\"Cool\"},{\"date\":\"2021-09-13T20:44:48.0992701-03:00\",\"temperatureC\":3,\"temperatureF\":37,\"summary\":\"Freezing\"}]", "headers" : { "Date" : "Wed, 08 Sep 2021 23:44:47 GMT", "Content-Type" : "application/json; charset=utf-8", "Server" : "Kestrel" } }, "uuid" : "ef53ea56-f118-4b3a-8c69-a9484851d99a", "persistent" : true, "insertionIndex" : 1 } ``` -------------------------------- ### Library Usage Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/solutions/pact.md Example of using the WireMock Pact library programmatically within a test class. ```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(); } } ``` -------------------------------- ### Build Production Site Source: https://github.com/wiremock/wiremock.org/blob/main/README.md Builds the production-ready static site. ```bash pnpm build ``` -------------------------------- ### Install the WireMock CLI Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/solutions/ai.mdx Command to install the WireMock CLI using npm. ```bash npm i -g @wiremock/cli ``` -------------------------------- ### Basic Server and Rule Initialization Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/configuration.mdx Demonstrates how to initialize WireMockServer and WireMockRule with a specific port using options. ```java import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; WireMockServer wm = new WireMockServer(options().port(2345)); @Rule WireMockRule wm = new WireMockRule(options().port(2345)); ``` -------------------------------- ### Main proto file Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/request-matching-protobuf.md Example of a main proto file when using multiple proto definitions. ```proto syntax = "proto3"; import "request.proto"; package greet; service Greeter { rpc SayHello (HelloRequest) returns (HelloReply); } message HelloReply { string message = 1; } ``` -------------------------------- ### Preview Production Build Source: https://github.com/wiremock/wiremock.org/blob/main/README.md Locally previews the production build of the site. ```bash pnpm preview ``` -------------------------------- ### JsonPath.SelectToken in C# Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/response-templating.mdx Example of using JsonPath.SelectToken to extract data from the request body in a WireMock.Net C# setup. ```csharp var server = WireMockServer.Start(); server .Given(Request.Create().WithPath("/jsonpathtestToken").UsingPost()) .RespondWith(Response.Create() .WithHeader("Content-Type", "application/json") .WithBody("{{JsonPath.SelectToken request.body \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}") .WithTransformer() ); ``` -------------------------------- ### Go WireMock REST API Client Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/solutions/golang.mdx Example of using the Go WireMock client library to stub API resources via WireMock's Administrative REST API. ```go 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), )) } ``` -------------------------------- ### Basic stubbing example in Python Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/stubbing.mdx Python code to create a stub mapping for a GET request to /some/thing with a plain text response. ```python Mappings.create_mapping( Mapping( request=MappingRequest(method=HttpMethods.GET, url="/some/thing"), response=MappingResponse(status=200, body="Hello, world!", headers=("Content-Type", "text/plain")), ) ) ``` -------------------------------- ### Current date and time helpers Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/response-templating.mdx Examples of using the `now` helper to get the current date and time, with options for offset and formatting. ```handlebars {{now}} {{now offset='3 days'}} {{now offset='-24 seconds'}} {{now offset='1 years'}} {{now offset='10 years' format='yyyy-MM-dd'}} ``` -------------------------------- ### ProxyAndRecordSettings Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/settings.md Enables ProxyAndRecord functionality by defining ProxyAndRecordSettings and specifying a URL. ```csharp var server = WireMockServer.Start(new FluentMockServerSettings { Urls = new[] { "http://localhost:9095/" }, StartAdminInterface = true, ProxyAndRecordSettings = new ProxyAndRecordSettings { Url = "http://www.bbc.com", SaveMapping = true, SaveMappingToFile = true, BlackListedHeaders = new [] { "dnt", "Content-Length" }, BlackListedCookies = new [] { "c1", "c2" }, SaveMappingForStatusCodePattern = "2xx", AllowAutoRedirect = true, WebProxySettings = new WebProxySettings { UserName = "test", Password = "pwd", Address = "http://company.proxy" }, UseDefinedRequestMatchers = false, AppendGuidToSavedMappingFile = true, ReplaceSettings = new ProxyUrlReplaceSettings { "OldValue" = "old", "NewValue" = "new" } } }); ``` -------------------------------- ### Java GET_OR_HEAD method example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/stubbing.mdx Demonstrates how to use the getOrHead method in Java to stub requests matching both GET and HEAD HTTP methods. ```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)); } ``` -------------------------------- ### Stateful Workflows with Scenarios Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/solutions/service-virtualization.mdx Java example demonstrating stateful workflows using WireMock scenarios to model multi-step interactions where responses change based on previous states. ```java stubFor(post("/cart/checkout") .inScenario("Checkout") .whenScenarioStateIs(STARTED) .willReturn(ok().withBody("Processing")) .willSetStateTo("Completed")); stubFor(get("/cart/status") .inScenario("Checkout") .whenScenarioStateIs("Completed") .willReturn(ok().withBody("Order confirmed"))); ``` -------------------------------- ### Array add & remove helpers Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/response-templating.mdx Examples of using arrayAdd and arrayRemove helpers to manipulate array elements by position, 'start', or 'end'. ```handlebars {{arrayAdd (array 1 'three') 2 position=1}} // [1, 2, three] {{arrayAdd (array 1 'three') 2 position='start'}} // [2, 1, three] {{arrayAdd (array 1 'three') 2 position='end'}} // [1, three, 2] {{arrayAdd (array 1 'three') 2}} // [1, three, 2] {{arrayRemove (array 1 2 'three') position=1}} // [1, three] {{arrayRemove (array 1 2 'three') position='start'}} // [2, three] {{arrayRemove (array 1 2 'three') position='end'}} // [1, 2] {{arrayRemove (array 1 2 'three')}} // [1, 2] ``` -------------------------------- ### Steps Source: https://github.com/wiremock/wiremock.org/blob/main/STARLIGHT_PATTERNS.md Example of using the Steps component for ordered steps. ```mdx import { Steps } from '@astrojs/starlight/components'; 1. Install WireMock 2. Configure your test 3. Run your test ``` -------------------------------- ### Customizing WireMock Rule with Options Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/quickstart/java-junit.mdx Example of customizing WireMock rule with specific port numbers. ```java import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig(); ... @Rule public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().port(8089).httpsPort(8443)); ``` -------------------------------- ### Building your own image Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/standalone/docker.mdx A sample Dockerfile that extends the official WireMock image, copies local configuration files, and overrides the entrypoint to pass custom startup parameters. ```Dockerfile # Sample Dockerfile FROM wiremock/wiremock:latest COPY wiremock /home/wiremock ENTRYPOINT ["/docker-entrypoint.sh", "--global-response-templating", "--disable-gzip", "--verbose"] ``` -------------------------------- ### Current date and time in a specific timezone Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/response-templating.mdx Example of using the `now` helper to get the current date and time formatted for a specific timezone. ```handlebars {{now timezone='Australia/Sydney' format='yyyy-MM-dd HH:mm:ssZ'}} ``` -------------------------------- ### Docker Run Command Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/download-and-installation.mdx Run WireMock as a standalone service using Docker. ```bash docker run -it --rm -p 8080:8080 --name wiremock \ wiremock/wiremock:${VERSIONS.WIREMOCK_STABLE} ``` -------------------------------- ### Basic stubbing example in Golang Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/stubbing.mdx Golang code to stub a GET request to /some/thing, returning a plain text body and setting the Content-Type header. ```go wiremockClient.StubFor(wiremock.Get(wiremock.URLPathEqualTo("/some/thing")). WillReturnResponse( wiremock.NewResponse(). WithStatus(http.StatusOK). WithBody("Hello, world!"). WithHeader("Content-Type", "text/plain"))) ``` -------------------------------- ### Initializing WireMock Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/solutions/c_cpp.mdx Example of initializing a WireMock container using the Testcontainers for C/C++ module and setting up mappings. ```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; } // ... ``` -------------------------------- ### Programmatic Server Creation and Control Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/java-usage.md Demonstrates how to create, start, and stop a WireMock server instance directly in Java code. ```java WireMockServer wireMockServer = new WireMockServer(options().port(8089)); //No-args constructor will start on port 8080, no HTTPS wireMockServer.start(); // Sometime later wireMockServer.stop(); ``` -------------------------------- ### Random Text Generation in C# Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/response-templating.mdx Example of generating a random string of a specified length using the Random helper in WireMock.Net C# setup. ```csharp var server = WireMockServer.Start(); server .Given(Request.Create().WithPath("/random").UsingGet()) .RespondWith(Response.Create() .WithHeader("Content-Type", "application/json") .WithBodyAsJson( Text = "{{Random Type=\"Text\" Min=8 Max=20}}", ) .WithTransformer() ); ``` -------------------------------- ### Random Regex Generation in C# Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/response-templating.mdx Example of generating a random string based on a Regex pattern using the Xeger helper in WireMock.Net C# setup. ```csharp var server = FluentMockServer.Start(); server .Given(Request.Create().WithPath("/random-regex").UsingGet()) .RespondWith(Response.Create() .WithHeader("Content-Type", "application/json") .WithBodyAsJson( Text = "{{Xeger \"[1-9][0-9]{3}[A-Z]{2}\"}}", ) .WithTransformer() ); ``` -------------------------------- ### Get log entries via C# code Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/request-matching-tips.md This C# code snippet demonstrates how to start a WireMock server and access its log entries. ```csharp var server = WireMockServer.Start(); var logEntries = server.LogEntries; ``` -------------------------------- ### arrayJoin helper - with prefix and suffix Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/response-templating.mdx Examples showing how to use the arrayJoin helper with 'prefix' and 'suffix' parameters to add characters to the start and end of the joined string. ```handlebars {{arrayJoin ',' (array 'One' 'Two' 'Three') prefix='[' suffix=']'}} // [One,Two,Three] {{arrayJoin ' * ' (array 1 2 3) prefix='(' suffix=')'}} // (1 * 2 * 3) ``` -------------------------------- ### Configuring static DSL Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/junit-jupiter.mdx Example of configuring the WireMock extension to use the static DSL. ```java public class AutomaticStaticDslConfigTest { @RegisterExtension static WireMockExtension wm1 = WireMockExtension.newInstance() .options(wireMockConfig().dynamicPort().dynamicHttpsPort()) .configureStaticDsl(true) .build(); @RegisterExtension static WireMockExtension wm2 = WireMockExtension.newInstance() .options(wireMockConfig().dynamicPort().dynamicHttpsPort()) .build(); @Test void test_something_with_wiremock() { // Will communicate with the instance called wm1 stubFor(get("/static-dsl").willReturn(ok())); // Do test stuff... } } ``` -------------------------------- ### Basic stubbing example in Java Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/stubbing.mdx Java code to stub a GET request to /some/thing, returning a plain text body and setting the Content-Type header. It also asserts that requests to /some/thing/else return 404. ```java @Test public void exactUrlOnly() { stubFor(get(urlEqualTo("/some/thing")) .willReturn(aResponse() .withHeader("Content-Type", "text/plain") .withBody("Hello world!"))); assertThat(testClient.get("/some/thing").statusCode(), is(200)); assertThat(testClient.get("/some/thing/else").statusCode(), is(404)); } ``` -------------------------------- ### Other proto file Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/request-matching-protobuf.md Example of an imported proto file when using multiple proto definitions. ```proto // request.proto syntax = "proto3"; package greet; message HelloRequest { string name = 1; } ``` -------------------------------- ### Python Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/solutions/testcontainers.mdx Example of using wiremock_container with pytest in Python. ```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" ``` -------------------------------- ### FluentBuilder Example for Mapping Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/admin-api-reference.md Demonstrates how to use the FluentBuilder to construct a WireMock mapping definition. ```csharp var mappingBuilder = api.GetMappingBuilder(); mappingBuilder.Given(m => m .WithTitle("This is my title 1") .WithRequest(req => req .UsingGet() .WithPath("/bla1") ) .WithResponse(rsp => rsp .WithBody("x1") .WithHeaders(h => h.Add("h1", "v1")) ) ); ``` -------------------------------- ### Java Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/solutions/testcontainers.mdx Example of using WireMockContainer with JUnit 5 in Java. ```java import org.junit.jupiter.api.*; import org.testcontainers.junit.jupiter.*; import org.wiremock.integrations.testcontainers.testsupport.http.*; import static org.assertj.core.api.Assertions.assertThat; @Testcontainers class WireMockContainerJunit5Test { @Container WireMockContainer wiremockServer = new WireMockContainer("2.35.0") .withMapping("hello", WireMockContainerJunit5Test.class, "hello-world.json"); @Test void helloWorld() throws Exception { String url = wiremockServer.getUrl("/hello"); HttpResponse response = new TestHttpClient().get(url); assertThat(response.getBody()) .as("Wrong response body") .contains("Hello, world!"); } } ``` -------------------------------- ### Docker Compose - Mounting Files Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/standalone/docker.mdx A sample Docker Compose file demonstrating how to mount local directories for extensions, __files, and mappings into the WireMock container. ```yaml # Sample compose file version: "3" services: wiremock: image: "wiremock/wiremock:latest" container_name: my_wiremock volumes: - ./extensions:/var/wiremock/extensions - ./__files:/home/wiremock/__files - ./mappings:/home/wiremock/mappings entrypoint: ["/docker-entrypoint.sh", "--global-response-templating", "--disable-gzip", "--verbose"] ``` -------------------------------- ### C# Example for using Handlebars.Net Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/response-templating.mdx WireMock.Net C# code demonstrating how to set up a response with a Handlebars.Net transformer. ```csharp var server = WireMockServer.Start(); server .Given( Request.Create().WithPath("/some/thing").UsingGet() ) .RespondWith( Response.Create() .WithBody("Hello world! Your path is {{request.path}}.") .WithTransformer() ); ``` -------------------------------- ### Post Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/wiremock-java-compatibility.md An example of a Wiremock Java mapping for a POST request. ```json { "id" : "365dd908-dc67-4f27-9e41-15d908206d81", "name" : "weatherforecast_register-city", "request" : { "url" : "/WeatherForecast/register-city", "method" : "POST", "bodyPatterns" : [ { "equalToJson" : "{ \"cityName\": \"São Paulo\", \"cityCode\": 5001 }", "ignoreArrayOrder" : true, "ignoreExtraElements" : true } ] }, "response" : { "status" : 200, "headers" : { "Date" : "Wed, 08 Sep 2021 23:48:33 GMT", "Server" : "Kestrel" } }, "uuid" : "365dd908-dc67-4f27-9e41-15d908206d81", "persistent" : true, "insertionIndex" : 4 } ``` -------------------------------- ### Creating a simple, single webhook (JSON) Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/webhooks-and-callbacks.md This JSON configuration demonstrates how to set up a simple webhook to a fixed URL with fixed data. ```json { "request": { "urlPath": "/something-async", "method": "POST" }, "response": { "status": 200 }, "serveEventListeners": [ { "name": "webhook", "parameters": { "method": "POST", "url": "http://my-target-host/callback", "headers": { "Content-Type": "application/json" }, "body": "{ \"result\": \"SUCCESS\" }" } } ] } ``` -------------------------------- ### Docker Compose - Basic Configuration Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/standalone/docker.mdx A sample Docker Compose file defining a WireMock service with a custom entrypoint to pass startup parameters. ```yaml # Sample compose file version: "3" services: wiremock: image: "wiremock/wiremock:latest" container_name: my_wiremock entrypoint: ["/docker-entrypoint.sh", "--global-response-templating", "--disable-gzip", "--verbose"] ``` -------------------------------- ### Configuring Static Client with Imports Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/java-usage.md Example of configuring the static WireMock client, including necessary imports for DSL usage. ```java import static com.github.tomakehurst.wiremock.client.WireMock.*; configureFor("wiremock.host", 8089); stubFor(get(....)); ``` -------------------------------- ### Example matching JSON Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/request-matching-jsonpartialmatcher.md Examples of JSON payloads that would be matched by JsonPartialMatcher. ```json // matching { "test": "abc" } // also matching { "test": "abc", "extra": "?" } ``` -------------------------------- ### C# MimePartMatcher Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/request-matching-mimepartmatcher.md This C# code demonstrates how to create and use MimePartMatcher instances to match different parts of a multipart MIME request. ```csharp var textPlainContentTypeMatcher = new ContentTypeMatcher("text/plain"); var textPlainContentMatcher = new ExactMatcher("This is some plain text"); var textPlainMatcher = new MimePartMatcher(MatchBehaviour.AcceptOnMatch, textPlainContentTypeMatcher, null, null, textPlainContentMatcher); var partTextJsonContentTypeMatcher = new ContentTypeMatcher("text/json"); var partTextJsonContentMatcher = new JsonMatcher(new { Key = "Value" }, true); var partTextMatcher = new MimePartMatcher(MatchBehaviour.AcceptOnMatch, partTextJsonContentTypeMatcher, null, null, partTextJsonContentMatcher); var imagePngContentTypeMatcher = new ContentTypeMatcher("image/png"); var imagePngContentDispositionMatcher = new ExactMatcher("attachment; filename=\"image.png\""); var imagePngContentTransferEncodingMatcher = new ExactMatcher("base64"); var imagePngContentMatcher = new ExactObjectMatcher(Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAIAAAACAgMAAAAP2OW3AAAADFBMVEX/tID/vpH/pWX/sHidUyjlAAAADElEQVR4XmMQYNgAAADkAMHebX3mAAAAAElFTkSuQmCC")); var imagePngMatcher = new MimePartMatcher(MatchBehaviour.AcceptOnMatch, imagePngContentTypeMatcher, imagePngContentDispositionMatcher, imagePngContentTransferEncodingMatcher, imagePngContentMatcher); var matchers = new IMatcher[] { textPlainMatcher, partTextMatcher, imagePngMatcher }; server .Given(Request.Create() .WithPath("/multipart") .UsingPost() .WithMultiPart(matchers) ) .WithGuid("b9c82182-e469-41da-bcaf-b6e3157fefdb") .RespondWith(Response.Create() .WithBody("MultiPart is ok") ); ``` -------------------------------- ### Option 2: Using WireMock.Net.StandAlone library with settings Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/wiremock-as-a-standalone-process.md Launches a WireMock standalone server using the WireMock.Net.StandAlone library with custom settings. ```csharp class Program { static void Main(string[] args) { // see source code for all the possible properties var settings = new WireMockServerSettings { AllowPartialMapping=true, StartAdminInterface=true }; StandAloneApp.Start(settings); Console.WriteLine("Press any key to stop the server"); Console.ReadKey(); } } ``` -------------------------------- ### ResponseTemplateTransformer Java Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/response-templating.mdx Example of using ResponseTemplateTransformer to add permitted extensions to a rule. ```java @Rule public WireMockRule wm = new WireMockRule(options() .dynamicPort() .withRootDirectory(defaultTestFilesRoot()) .extensions(new ResponseTemplateTransformer( getTemplateEngine(), options.getResponseTemplatingGlobal(), getFiles(), templateModelProviders ) ) ); ``` -------------------------------- ### Matching and Not Matching Examples Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/request-matching-jsonmatcher.md Provides examples of JSON payloads that match and do not match the JsonMatcher. ```json // matching { "x": 42, "s": "s" } ``` ```json // not matching { "x": 42, "s": "?" } ``` ```json // matching { "X": 42, "s": "S" } ``` -------------------------------- ### Gradle Dependencies Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/quickstart/java-junit.mdx Dependencies for WireMock and AssertJ for testing in Gradle. ```groovy testImplementation "org.wiremock:wiremock:${VERSIONS.WIREMOCK_STABLE}" testImplementation "org.assertj:assertj-core:3.24.2" ``` -------------------------------- ### JSON Mapping Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/request-matching-jsonpathmatcher.md Example of configuring JsonPathMatcher within a JSON mapping file. ```json { "Guid": "e4a600b8-9d6f-453f-90c6-3db2b0885ddb", "Request": { "Path": { "Matchers": [ { "Name": "WildcardMatcher", "Pattern": "/jsonpath", "IgnoreCase": false } ] }, "Methods": [ "put" ], "Body": { "Matcher": { "Name": "JsonPathMatcher", "Pattern": "$.things[?(@.name == 'RequiredThing')]" } } }, "Response": { "StatusCode": 200, "BodyDestination": "SameAsSource", "Body": "{ \"result\": \"JsonPathMatcher !!!\"}", "UseTransformer": false } } ``` -------------------------------- ### Running with extensions Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/standalone/docker.mdx This command starts a WireMock container, mounts a local 'extensions' directory to `/var/wiremock/extensions`, and enables the Webhooks extension via a CLI parameter. ```sh docker run -it --rm \ -p 8080:8080 \ --name wiremock \ -v $PWD/extensions:/var/wiremock/extensions \ wiremock/wiremock \ --extensions org.wiremock.webhooks.Webhooks ``` -------------------------------- ### Fetch response from JSON file stub Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/standalone/java-jar.mdx Example of fetching a response after setting up a stub using a JSON file. ```bash $ curl http://localhost:8080/api/mytest ``` -------------------------------- ### JSON Configuration Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/dotnet/kestrelserveroptions.md Example of how KestrelServerOptions and their limits can be overridden using a JSON configuration structure. ```json { "Kestrel": { "Limits": { "MaxRequestBodySize": 30000000, "MaxRequestHeadersTotalSize": 32768 }, "DisableStringReuse": true } } ``` -------------------------------- ### Response Templating Example Source: https://github.com/wiremock/wiremock.org/blob/main/src/content/docs/docs/websockets.mdx Example of using Handlebars templating in a WebSocket message response to personalize the greeting. ```java sendMessage("Hello {{jsonPath message.body '$.name'}}, welcome!") .onOriginatingChannel() ```