https://github.com/JasonRowe/KestrelMock
https://www.nuget.org/packages/KestrelMock
There are many powerful mocking frameworks available why build another one? Sure frameworks like WireMock and MounteBank have a bunch of fancy features but who really needs all that. Seriously though sometimes all you need is a response based on URL and post data ridiculously fast. Also a Kestrel mock HTTP server can spin up inline with your .NET Core tests quick on Windows or Linux.
Install
dotnet add package KestrelMock
Example Use
var config = new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: false).Build(); KestrelMock.RunAsync(config);
What is Kestrel?
Kestral was built as part of the .NET Core initiative to be a cross platform HTTP server. I think of Kestrel as the HTTP server you use when hosting .NET Core apps. It’s is super light weight and fast. If you are familiar with IIS or IIS Express it is a replacement for that without all the baggage. Also the .NET Core framework has friendly syntax for firing up a server using web host or generic host.
How does it work?
All the following words in this post are just fluff built around the following lines of code.
WebHost.CreateDefaultBuilder() .UseConfiguration(configuration) .UseUrls(urls.ToArray()) .UseStartup<Startup>();
What this line does is startup a server using a startup class named “KestrelMock”. The “KestrelMock” classes job will be to read in the mock setting from the “IConfiguration” and setup the expected HTTP responses. For my naive mock framework, I’ll just implement some pretty standard matching conventions.
- URL path matches
- URL path starts with
- POST body contains
- POST body does not contain
You would be surprised how many scenarios can be handle with these simple matching conventions.
Configuration
To keep the mocking simple here is an example configuration used for setting up a mock HTTP endpoint. It has a “Request” where you configure the matching conventions and a “Response” where you put in the results you want from the server.
{ "Request":{ "Methods":[ "GET" ], "PathStartsWith":"/starts/with" }, "Response":{ "Status":200, "Headers":[ { "Content-Type":"application/json" } ], "Body":"{\"banana_x\": 8000}" } }
Leave a Reply