“The core feature of WireMock is the ability to return predefined HTTP responses for requests matching criteria.”
I would create these Mocks (Stubs really) grouped by feature, ie: MyWorker\stubs\MyWorker.Stubs\Services\FooService which is the same logical manner we group class files in code.
Setup Project
The simplest way is to use BackgroundService running in a console application
Use the VS GUI scaffold to create a new Console Application
Create all the WireMockServer‘s using avalible ports, we normally call this file Stubs.cs, the example below will create wire mock servers on ports 6010 & 6020. These represent Restful APIs your application will interact with in development and/or under test. You would configure these in appsettings.Development.json / appsettings.Test.json.
Beside the simple var request = Request.Create().UsingGet() ... there are other methods in the fluent API.
ExactMatcher
1 2 3 4 5
var request = Request .Create() .UsingPost() .WithHeader(HeaderConstants.ClientName, new ExactMatcher(TestConstants.SomeKnownClientName)) .WithPath("/foos");
RegexMatcher
1 2 3 4 5 6
var request = Request .Create() .UsingPost() .WithPath("/foo.svc") .WithHeader("SOAPAction", new RegexMatcher(".*/somepath/someaction")) .WithBody(new XPathMatcher($"//*[local-name() = 'fooID'][text()='{KnownFoos.MyKnownFooId.ToString()}']"))
JsonPartialMatcher
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var ignoreCase = true; var options = new JsonSerializerOptions() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, Converters = { new JsonStringEnumConverter() } }; var matchOn = JsonSerializer.Serialize(partialMatchObject, options);
var request = Request .Create() .UsingPost() .WithPath("/foos") .WithBody(new JsonPartialMatcher(matchOn, ignoreCase));
Docker
Do you even code if you dont package up your things into a nice container :D
Create the Stubs.Dockerfile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build-env