WireMock.Net Documentation

repository·master·Indexed 23 days ago

https://github.com/wiremock/wiremock.net

A .NET port of the WireMock tool for mocking HTTP services, used to simulate API dependencies in unit, integration, and distributed system tests. It supports stubbing, record/playback proxying, and stateful behavior simulation. Key features include support for GraphQL, gRPC/ProtoBuf, OpenAPI, WebSockets, and OpenTelemetry. It can be deployed as a standalone process, Windows service, Docker container, or within IIS and Azure. The library provides a fluent C# API and various NuGet packages for integration with xUnit, NUnit, TUnit, and .NET Aspire.

Tokens
4.3K
Snippets
12
Records
25
Agent score
80%

What's inside WireMock.Net

  1. Overview of WireMock.Net features

    master

    WireMock.Net is a C# .NET implementation of the WireMock functionality, designed to mimic the original Java-based WireMock. It allows you to mock HTTP services for unit and integration testing.

    Key capabilities include:

    • Stubbing: Mock HTTP responses based on URL/Path, headers, cookies, and body content patterns.
    • Deployment Modes: Can run as a standalone process, Windows service, Azure/IIS, or within Docker.
    • Configuration: Configurable via a fluent C# .NET API, JSON files, or JSON over HTTP.
    • Advanced Mocking: Supports record/playback (proxying), per-request conditional proxying, and stateful behavior simulation.
    • Response Manipulation: Uses Handlebars and extensions for response templating and transformation.
    • Protocol Support: Includes support for GraphQL, gRPC/ProtoBuf, OpenAPI, WebSockets, and OpenTelemetry.
    • Testing Scenarios: Suitable for local development, CI/CD pipelines, and Aspire Distributed Application testing.
  2. WebSocket capabilities demonstrated in examples

    master

    The WireMock.Net WebSocket examples demonstrate several key capabilities:

    • Echo Server: Returns all received messages back to the client.
    • Custom Message Handlers: Implements complex logic (e.g., a chat server with commands like /help, /time, /upper).
    • Broadcast: Sends messages received from one client to all other connected clients.
    • Scenarios/State Machines: Manages state transitions (e.g., a game server moving from Lobby -> Playing -> GameOver).
    • WebSocket Proxy: Forwards WebSocket connections to external servers (e.g., echo.websocket.org).
    • Protocol Negotiation: Supports Sec-WebSocket-Protocol negotiation.
    • JSON Messaging: Handles structured data exchange.
    • Connection Management: Tracks and manages active connections and states.
  3. Ways to use WireMock.Net

    master

    WireMock.Net is highly versatile and can be integrated into your workflow in several ways:

    Testing Integrations

    • Unit Testing: Use WireMock.Net directly within your favorite .NET test framework.
    • Testcontainers.DotNet: Build and run WireMock.Net inside a Docker container for unit or integration testing.
    • .NET Aspire: Use WireMock.Net.Aspire to run WireMock.Net as an Aspire Hosted application for distributed testing.

    Deployment and Execution

    • dotnet tool: Install as a (global) dotnet tool for CLI usage.
    • Standalone Process: Launch the mock server as a standalone console application.
    • Windows Service: Run WireMock.Net as a background Windows Service.
    • Cloud/Web Hosting: Deploy as an Azure Web Job, an Azure Web App, or an application in IIS.
    • Docker: Use the official Linux or Windows-Nano containers available on Docker Hub.

    Security

    • HTTPS/SSL: WireMock.Net supports HTTPS/SSL for secure communication.
  4. Configure Custom TracerProvider for OpenTelemetry

    master

    If you require manual control over your TracerProvider configuration, you can use the AddWireMockInstrumentation extension method on a TracerProviderBuilder. This adds the WireMock.Net ActivitySource to your existing tracing pipeline.

    using OpenTelemetry;
    using OpenTelemetry.Trace;
    using WireMock.OpenTelemetry;
    
    var openTelemetryOptions = new OpenTelemetryOptions();
    
    // Configure your own TracerProvider
    using var tracerProvider = Sdk.CreateTracerProviderBuilder()
        .AddWireMockInstrumentation(openTelemetryOptions) // Adds WireMock.Net source
        .AddOtlpExporter(options =>
        {
            options.Endpoint = new Uri("http://localhost:4317");
        })
        .Build();
  5. Test WebSocket endpoints with wscat

    master

    The wscat CLI tool is recommended for manual testing of WebSocket endpoints. You can connect to standard endpoints, specify sub-protocols, or include custom headers.

    Common commands:

    Connect to a standard echo endpoint:

    wscat -c ws://localhost:9091/ws/echo

    Connect using a specific sub-protocol:

    wscat -c ws://localhost:9091/ws/protocol -s chat

    Connect with custom HTTP headers:

    wscat -c ws://localhost:9091/ws/echo -H "X-Custom-Header: value"
  6. Run WireMock.Net in IIS

    master

    To run a WireMock.Net Web Application within Internet Information Services (IIS), you must configure the hosting environment for ASP.NET Core. This typically involves:

    1. Following standard ASP.NET Core deployment patterns for IIS.
    2. Creating a web.config file in the application root to define the IIS handler and module settings.

    For detailed deployment guidance, refer to the Microsoft documentation on IIS support for ASP.NET Core or West Wind's guides on publishing ASP.NET Core applications to IIS.

  7. Quick Start with WireMockRouter

    master

    To begin using the routing extensions, start a WireMockServer and wrap it in a WireMockRouter. You can then use MapGet to define simple endpoints that return strings or other objects.

    using System.Net.Http.Json;
    using WireMock.Net.Extensions.Routing;
    using WireMock.Net.Extensions.Routing.Extensions;
    using WireMock.Server;
    
    var server = WireMockServer.Start();
    var router = new WireMockRouter(server);
    
    router.MapGet("/hello", _ => "Hello, world!");
    
    using var client = server.CreateClient();
    var result = await client.GetFromJsonAsync<string>("/hello");
    // Hello, world!
  8. Configure OpenTelemetry via AdditionalServiceRegistration (Recommended)

    master

    The recommended way to integrate OpenTelemetry is by using the AdditionalServiceRegistration property within WireMockServerSettings. This allows you to register OpenTelemetry services directly into the service collection used by the WireMock server.

    To enable tracing, you must also set ActivityTracingOptions in WireMockServerSettings to a non-null value. This tells WireMock.Net to create System.Diagnostics.Activity objects for requests.

    using WireMock.OpenTelemetry;
    using WireMock.Server;
    using WireMock.Settings;
    
    var openTelemetryOptions = new OpenTelemetryOptions
    {
        ExcludeAdminRequests = true,
        OtlpExporterEndpoint = "http://localhost:4317" // Your OTEL collector
    };
    
    var settings = new WireMockServerSettings
    {
        // Setting ActivityTracingOptions (not null) enables activity creation in middleware
        ActivityTracingOptions = new ActivityTracingOptions
        {
            ExcludeAdminRequests = true,
            RecordRequestBody = false, // PII concern
            RecordResponseBody = false, // PII concern
            RecordMatchDetails = true
        },
        AdditionalServiceRegistration = services =>
        {
            services.AddWireMockOpenTelemetry(openTelemetryOptions);
        }
    };
    
    var server = WireMockServer.Start(settings);