Jason Rowe

Be curious! Choose your own adventure.

KestrelMock .Net Core Mock Server

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.

  1. URL path matches
  2. URL path starts with
  3. POST body contains
  4. 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}"
   }
}

Posted

in

by

Comments

8 responses to “KestrelMock .Net Core Mock Server”

  1. Noah Caron Avatar
    Noah Caron

    This solution is simple, lightweight, and fast and allows for some pretty flexible testing scenarios for a given service.

  2. Gurmeet Singh Avatar
    Gurmeet Singh

    In my application, i call various Rest endpoints using a third party framework called Refit
    https://github.com/reactiveui/refit

    When i try to mock that api using KestralMock , Upon execution the api call remains in the
    Result = “Not Yet Computed” and status “WaitingForActivation” state
    and hence the code throws an exception when trying to retrieve the response data.

    Where as if i try to create an HttpClient similar to samples given in your code it works .

  3. Jason Avatar
    Jason

    I know some of the confusion was the default port of KestralMock (http://localhost:60000). Refit issues are now resolved.

  4. Gary Newport Avatar
    Gary Newport

    So how do I call this from within a test solution ?

  5. Jason Avatar
    Jason

    The best option would be to use docker. Here is an example.

    FROM jasonrowe/kestrelmock as KestrelMockServerBase
    WORKDIR /app
    COPY ["responses","responses"]
    COPY ["appsettings.json", "appsettings.json"]
    ENTRYPOINT ["dotnet", "KestrelMockServer.dll"]

  6. Jason Avatar
    Jason

    As of version 0.3.0, you can use RunAsync in a test project. That way the server can start in the background and then you can run tests. This would be if you don’t want to use docker to host this web server outside the project.

    KestrelMock.RunAsync(yourConfig);

    Run your tests after you do RunAsync

  7. Oleksiy Avatar
    Oleksiy

    hi, is there a way to return different status codes for the same endpoint?
    for example I have a GET request and I want to run 3 tests, one that mock 200 response, second one mocks 400,and 3rd one mocks 404. Is there a way to have all 3 in application json and how can I tell kestrelmock which one to return ?

  8. Jason Avatar
    Jason

    Glad you asked this… I was currently trying to decide how to support sequences. If you can’t change the URL during the request I think this would fit your needs. I’ll take this into consideration and feel free to help design this feature.

    https://github.com/JasonRowe/KestrelMock/issues/42

Leave a Reply

Your email address will not be published. Required fields are marked *