WireMock.Net

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()    
    .WithPath("/test")
    .UsingGet();

var response = Response.Create()
    .WithStatusCode(200)
    .WithBody("aaa");

WireMockServer wireMockServer = WireMockServer.Start(1234);
wireMockServer
    .Given(request)
    .RespondWith(response);


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

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.

References

https://pcholko.com/posts/2021-04-05/wiremock-integration-test/



Profile picture

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

© Paul Michaels 2024