RichardSzalay.MockHttp 7.0.0

dotnet add package RichardSzalay.MockHttp --version 7.0.0                
NuGet\Install-Package RichardSzalay.MockHttp -Version 7.0.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="RichardSzalay.MockHttp" Version="7.0.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add RichardSzalay.MockHttp --version 7.0.0                
#r "nuget: RichardSzalay.MockHttp, 7.0.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install RichardSzalay.MockHttp as a Cake Addin
#addin nuget:?package=RichardSzalay.MockHttp&version=7.0.0

// Install RichardSzalay.MockHttp as a Cake Tool
#tool nuget:?package=RichardSzalay.MockHttp&version=7.0.0                

NuGetNuGet

MockHttp for HttpClient

MockHttp is a testing layer for Microsoft's HttpClient library. It allows stubbed responses to be configured for matched HTTP requests and can be used to test your application's service layer.

NuGet

PM> Install-Package RichardSzalay.MockHttp

How?

MockHttp defines a replacement HttpMessageHandler, the engine that drives HttpClient, that provides a fluent configuration API and provides a canned response. The caller (eg. your application's service layer) remains unaware of its presence.

Usage

var mockHttp = new MockHttpMessageHandler();

// Setup a respond for the user api (including a wildcard in the URL)
mockHttp.When("http://localhost/api/user/*")
        .Respond("application/json", "{'name' : 'Test McGee'}"); // Respond with JSON

// Inject the handler or client into your application code
var client = mockHttp.ToHttpClient();

var response = await client.GetAsync("http://localhost/api/user/1234");
// or without async: var response = client.GetAsync("http://localhost/api/user/1234").Result;

var json = await response.Content.ReadAsStringAsync();

// No network connection required
Console.Write(json); // {'name' : 'Test McGee'}

When (Backend Definitions) vs Expect (Request Expectations)

MockHttpMessageHandler defines both When and Expect, which can be used to define responses. They both expose the same fluent API, but each works in a slightly different way.

Using When specifies a "Backend Definition". Backend Definitions can be matched against multiple times and in any order, but they won't match if there are any outstanding Request Expectations present (unless BackendDefinitionBehavior.Always is specified). If no Request Expectations match, Fallback will be used.

Using Expect specifies a "Request Expectation". Request Expectations match only once and in the order they were added in. Only once all expectations have been satisfied will Backend Definitions be evaluated. Calling mockHttp.VerifyNoOutstandingExpectation() will assert that there are no expectations that have yet to be called. Calling ResetExpectations clears the the queue of expectations.

This pattern is heavily inspired by AngularJS's $httpBackend

Matchers (With*)

The With and Expect methods return a MockedRequest, which can have additional constraints (called matchers) placed on them before specifying a response with Respond.

Passing an HTTP method and URL to When or Expect is equivalent to applying a Method and Url matcher respectively. The following chart breaks down additional built in matchers and their usage:

Method Description
<pre>WithQueryString("key", "value")<br /><br />WithQueryString("key=value&other=value")<br /><br />WithQueryString(new Dictionary<string,string><br />{<br /> { "key", "value" },<br /> { "other", "value" }<br />}<br /></pre> Matches on one or more querystring values, ignoring additional values
<pre>WithExactQueryString("key=value&other=value")<br /><br />WithExactQueryString(new Dictionary<string,string><br />{<br /> { "key", "value" },<br /> { "other", "value" }<br />}<br /></pre> Matches on one or more querystring values, rejecting additional values
<pre>WithFormData("key", "value")<br /><br />WithFormData("key=value&other=value")<br /><br />WithFormData(new Dictionary<string,string><br />{<br /> { "key", "value" },<br /> { "other", "value" }<br />})<br /></pre> Matches on one or more form data values, ignoring additional values
<pre>WithExactFormData("key=value&other=value")<br /><br />WithExactFormData(new Dictionary<string,string><br />{<br /> { "key", "value" },<br /> { "other", "value" }<br />})<br /></pre> Matches on one or more form data values, rejecting additional values
<pre>WithContent("{'name':'McGee'}")</pre> Matches on the (post) content of the request
<pre>WithPartialContent("McGee")</pre> Matches on the partial (post) content of the request
<pre>WithHeaders("Authorization", "Basic abcdef")<br /><br />WithHeaders(@"Authorization: Basic abcdef<br />Accept: application/json")<br /><br />WithHeaders(new Dictionary<string,string><br />{<br /> { "Authorization", "Basic abcdef" },<br /> { "Accept", "application/json" }<br />})<br /></pre> Matches on one or more HTTP header values
<pre>WithJsonContent<T>(new MyTypedRequest() [, jsonSerializerSettings])<br /><br />WithJsonContent<T>(t ⇒ t.SomeProperty == 5 [, jsonSerializerSettings])</pre> Matches on requests that have matching JSON content
<pre>With(request ⇒ request.Content.Length > 50)</pre> Applies custom matcher logic against an HttpRequestMessage

These methods are chainable, making complex requirements easy to descirbe.

Verifying Matches

When using Request Expectations via Expect, MockHttpMessageHandler.VerifyNoOutstandingExpectation() can be used to assert that there are no unmatched requests.

For other use cases, GetMatchCount will return the number of times a mocked request (returned by When / Expect) was called. This even works with Fallback, so you can check how many unmatched requests there were.

var mockHttp = new MockHttpMessageHandler();

var request = mockHttp.When("http://localhost/api/user/*")
        .Respond("application/json", "{'name' : 'Test McGee'}");

var client = mockHttp.ToHttpClient();

await client.GetAsync("http://localhost/api/user/1234");
await client.GetAsync("http://localhost/api/user/2345");
await client.GetAsync("http://localhost/api/user/3456");

Console.Write(mockHttp.GetMatchCount(request)); // 3

Match Behavior

Each request is evaluated using the following process:

  1. If Request Expectations exist and the request matches the next expectation in the queue, the expectation is used to process the response and is then removed from the queue
  2. If no Request Expectations exist, or the handler was constructed with BackendDefinitionBehavior.Always, the first matching Backend Definition processes the response
  3. MockHttpMessageHandler.Fallback handles the request

Fallback

The Fallback property handles all requests that weren't handled by the match behavior. Since it is also a mocked request, any of the Respond overloads can be applied.

// Unhandled requests should throw an exception
mockHttp.Fallback.Throw(new InvalidOperationException("No matching mock handler"));

// Unhandled requests should be executed against the network
mockHttp.Fallback.Respond(new HttpClient());

The default fallback behavior is to throw an exception that summarises why reach mocked request failed to match.

Examples

This example uses Expect to test an OAuth ticket recycle process:

// Simulate an expired token
mockHttp.Expect("/users/me")
        .WithQueryString("access_token", "old_token")
        .Respond(HttpStatusCode.Unauthorized);
    
// Expect the request to refresh the token and supply a new one
mockHttp.Expect("/tokens/refresh")
        .WithFormData("refresh_token", "refresh_token")
        .Respond("application/json", "{'access_token' : 'new_token', 'refresh_token' : 'new_refresh'}");
    
// Expect the original call to be retried with the new token
mockHttp.Expect("/users/me")
        .WithQueryString("access_token", "new_token")
        .Respond("application/json", "{'name' : 'Test McGee'}");
    
var httpClient = mockHttp.ToHttpClient();

var userService = new UserService(httpClient);

var user = await userService.GetUserDetails();

Assert.Equals("Test McGee", user.Name);
mockHttp.VerifyNoOutstandingExpectation();

Platform Support

MockHttp 7.0.0 and later are compiled for .NET 6, .NET 5, .NET Standard 2.0, .NET Standard 1.1

MockHttp 6.0.0 has increased legacy platform support and can still be used, but is no longer updated with new features.

Build / Release

Clone the repository and build RichardSzalay.MockHttp.sln using MSBuild. NuGet package restore must be enabled.

To release, build:

dotnet pack -c Release --no-build ./RichardSzalay.MockHttp/RichardSzalay.MockHttp.csproj

If you fork the project, simply rename the nuspec file accordingly and it will be picked up by the release script.

Contributors

Many thanks to all the members of the community that have contributed PRs to this project:

License

The MIT License (MIT)

Copyright (c) 2023 Richard Szalay

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp1.0 was computed.  netcoreapp1.1 was computed.  netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard1.1 is compatible.  netstandard1.2 was computed.  netstandard1.3 was computed.  netstandard1.4 was computed.  netstandard1.5 was computed.  netstandard1.6 was computed.  netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net45 was computed.  net451 was computed.  net452 was computed.  net46 was computed.  net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen30 was computed.  tizen40 was computed.  tizen60 was computed. 
Universal Windows Platform uap was computed.  uap10.0 was computed. 
Windows Phone wpa81 was computed. 
Windows Store netcore was computed.  netcore45 was computed.  netcore451 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 1.1

  • .NETStandard 2.0

    • No dependencies.
  • net5.0

    • No dependencies.
  • net6.0

    • No dependencies.

NuGet packages (18)

Showing the top 5 NuGet packages that depend on RichardSzalay.MockHttp:

Package Downloads
D2L.Security.OAuth2.TestFramework

Library for obtaining authorization in tests

Kralizek.AutoFixture.Extensions.MockHttp

An extension to AutoFixture to easily work with MockHttp.

comsec.sugar.moq

A lean collection of classes to make it easier to mock multiple dependencies for a unit test.

Microsoft.Bot.Builder.Dialogs.Adaptive.Testing

Library for creating declarative test scripts for testing Bot Framework Adaptive Dialogs.

CoderPatros.MockHttpExtensions

This library is a small collection of extension methods for Richard Szalay's excellent MockHttp.

GitHub repositories (2)

Showing the top 2 popular GitHub repositories that depend on RichardSzalay.MockHttp:

Repository Stars
bitwarden/server
Bitwarden infrastructure/backend (API, database, Docker, etc).
restsharp/RestSharp
Simple REST and HTTP API Client for .NET
Version Downloads Last updated
7.0.0 4,579,633 10/12/2023
6.0.0 14,671,188 11/18/2019
5.0.0 2,026,914 6/18/2018
4.0.0 108,648 4/16/2018
3.3.0 183,895 3/11/2018
3.2.1 714,828 9/7/2017
3.2.0 25,537 8/31/2017
3.1.0 6,521 8/29/2017
1.5.1 30,008 8/22/2017
1.5.0 234,560 2/23/2017
1.4.1 13,271 1/19/2017
1.4.0 3,747 1/17/2017
1.3.1 93,269 9/19/2016
1.3.0 31,238 6/30/2016
1.3.0-netstandard-alpha2 6,603 5/19/2016
1.3.0-netstandard-alpha1 2,420 5/19/2016
1.2.2 71,842 3/1/2016
1.2.1 19,388 5/6/2015
1.2.0 16,056 12/22/2014
1.1.0 2,766 12/21/2014
1.0.1.79-pre 2,293 7/5/2016
1.0.1 22,528 6/28/2014
1.0.1-beta 2,255 6/23/2014
1.0.0-beta 2,259 6/22/2014

7.0.0 - Change target profiles to netstandard1.1, netstandard2.0, net5.0, net6.0 (BREAKING)
- Change default fallback behaviour to throw an exception with a report of the match attempts
- Add JSON and XML matchers
- Add support for synchronous HttpClient.Send #104
- Modernize source #41 and add SourceLink support #66
- Fix matching of encoded URL paths #116
- Throw a descriptive error when matching on a mocked request with no response #87 (thanks perfectsquircle!)
- Fix race condition on outstanding requests exception message #96 (thanks jr01!)
6.0.0 - Assemblies are now strong named (binary BREAKING) #1
5.0.0 - Align with official recommendations on multi-targetting HttpClient:
- Add netstandard2.0 target #61
- Change .NET 4.5 target to use in-band System.Net.Http reference (BREAKING) #61
- Remove PCL profile 111 (BREAKING) #18
4.0.0 - Default Fallback message now includes request method and URL (BREAKING)
- Deprecated FallbackMessage property removed (BREAKING)
3.3.0 - Added overloads for including custom headers in the response (thanks Sascha Kiefer!)
3.2.1 - XML documentation is now included in the NuGet package. Fixes #52
3.2.0 - MockHttpMessageHandler now tracks successful matches. Fixes #35
- Added WithExactQueryString / WithExactFormData overloads. Fixes #37
- Added BackendDefinitionBehavior to allow matching Backend Definitions when Request Expectations exist, but don't match. Fixes #45
- Fixed typo in Response(HttpResponseMessage) obsolete message. Fixes #44
3.1.0 - Bump major version. Fixes #50
1.5.1 - Respond(HttpClient) now works as expected. Fixes #39
- HttpResponseMessage can be disposed without breaking future requests. Fixes #33
1.5.0 - WithHeaders now also matches against Content-* headers (thanks Cory Lucas!)
1.4.0 - Cancellations and HttpClient timeouts are now supported. Fixes #29
- Added a .ToHttpClient() convenience method to HttpClientHandler
1.3.1 - Multiple requests to the same mocked handler now return unique response streams. Fixes #21
1.3.0 - Added support for .NET Core via the .NET Standard Library (1.1)
- Relative URLs now match correctly on Xamarin Android
1.2.2 - Root absolute URLs defined with no trailing flash now match those with a slash (and vice versa)
1.2.1 - HttpResponseMessage.RequestMessage is now assigned correctly
- Form/Query data matching now works with both + and %20 space encodings (thanks Jozef Izso!)
1.2.0 - Changed PCL profile to support WP8.1
1.1.0 - Added MockHttpMessageHandler.Fallback and HttpClient passthrough support