August 06, 2022

I was recently introduced to the WireMock.Net package. This is a .Net implementation of WireMock.

The basic idea where is that you can mock or stub a HTTP call. For example, you can tell it that when https://localhost:1234/test is called then a specific response should be returned - you could, for example, force it to error.

To get started, install the package:

install-package wiremock.net

This is a hefty package, so make sure it’s restricted to your test project.

The following code will replace the URL above with a response of “aaa”:

using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;

Console.WriteLine("Hello, World!");

var request = Request.Create()    

var response = Response.Create()

WireMockServer wireMockServer = WireMockServer.Start(1234);

HttpClient client = new HttpClient();
var result = await client.GetAsync("http://localhost:1234/test");
if (result != null && result.IsSuccessStatusCode)
    var output = await result.Content.ReadAsStringAsync();

I did, at first, try to run this for an actual site (e.g. to intercept google.com or something), but it won’t allow that, only localhost (at least, as far as I could see). A friend at work pointed out that, in a test, you would pass the URL in through the config anyway, and so you could change it to localhost.



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District

© Paul Michaels 2024