{"id":13431799,"url":"https://github.com/richardszalay/mockhttp","last_synced_at":"2025-05-14T11:13:27.749Z","repository":{"id":18040660,"uuid":"21084970","full_name":"richardszalay/mockhttp","owner":"richardszalay","description":"Testing layer for Microsoft's HttpClient library. Create canned responses using a fluent API.","archived":false,"fork":false,"pushed_at":"2024-11-30T01:35:19.000Z","size":256,"stargazers_count":1685,"open_issues_count":16,"forks_count":89,"subscribers_count":20,"default_branch":"master","last_synced_at":"2025-04-11T04:56:39.559Z","etag":null,"topics":["dotnet","dotnetcore","httpclient","mocking","testing"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/richardszalay.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-06-22T03:55:25.000Z","updated_at":"2025-04-10T18:39:10.000Z","dependencies_parsed_at":"2022-07-12T15:14:46.551Z","dependency_job_id":"fd650b87-de88-4f98-9bf1-eef4fbe6e706","html_url":"https://github.com/richardszalay/mockhttp","commit_stats":{"total_commits":137,"total_committers":13,"mean_commits":"10.538461538461538","dds":0.1897810218978102,"last_synced_commit":"4536be6b1582157ec33495e783362f0c089e4715"},"previous_names":[],"tags_count":20,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/richardszalay%2Fmockhttp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/richardszalay%2Fmockhttp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/richardszalay%2Fmockhttp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/richardszalay%2Fmockhttp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/richardszalay","download_url":"https://codeload.github.com/richardszalay/mockhttp/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254129529,"owners_count":22019628,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dotnet","dotnetcore","httpclient","mocking","testing"],"created_at":"2024-07-31T02:01:06.006Z","updated_at":"2025-05-14T11:13:27.722Z","avatar_url":"https://github.com/richardszalay.png","language":"C#","funding_links":[],"categories":["Frameworks, Libraries and Tools","C\\#","Libraries","框架, 库和工具","Testing","testing","dotnet"],"sub_categories":["Testing","测试"],"readme":"[![NuGet](http://img.shields.io/nuget/v/RichardSzalay.MockHttp.svg?style=flat-square)](https://www.nuget.org/packages/RichardSzalay.MockHttp/)[![NuGet](https://img.shields.io/nuget/dt/RichardSzalay.MockHttp.svg?style=flat-square)](https://www.nuget.org/packages/RichardSzalay.MockHttp/)\n\nMockHttp for HttpClient\n=====================\n\nMockHttp 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.\n\n## NuGet\n\n    PM\u003e Install-Package RichardSzalay.MockHttp\n\n## How?\n\nMockHttp 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.\n\n## Usage\n\n```csharp\nvar mockHttp = new MockHttpMessageHandler();\n\n// Setup a respond for the user api (including a wildcard in the URL)\nmockHttp.When(\"http://localhost/api/user/*\")\n        .Respond(\"application/json\", \"{'name' : 'Test McGee'}\"); // Respond with JSON\n\n// Inject the handler or client into your application code\nvar client = mockHttp.ToHttpClient();\n\nvar response = await client.GetAsync(\"http://localhost/api/user/1234\");\n// or without async: var response = client.GetAsync(\"http://localhost/api/user/1234\").Result;\n\nvar json = await response.Content.ReadAsStringAsync();\n\n// No network connection required\nConsole.Write(json); // {'name' : 'Test McGee'}\n```\n\n### When (Backend Definitions) vs Expect (Request Expectations)\n\n`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.\n\nUsing `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.\n\nUsing `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.\n\nThis pattern is heavily inspired by [AngularJS's $httpBackend](https://docs.angularjs.org/api/ngMock/service/$httpBackend)\n\n### Matchers (With*)\n\nThe `With` and `Expect` methods return a `MockedRequest`, which can have additional constraints (called matchers) placed on them before specifying a response with `Respond`.\n\nPassing 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:\n\n| Method | Description |\n| ------ | ----------- |\n| \u003cpre\u003eWithQueryString(\"key\", \"value\")\u003cbr /\u003e\u003cbr /\u003eWithQueryString(\"key=value\u0026other=value\")\u003cbr /\u003e\u003cbr /\u003eWithQueryString(new Dictionary\u0026lt;string,string\u003e\u003cbr /\u003e{\u003cbr /\u003e  { \"key\", \"value\" },\u003cbr /\u003e  { \"other\", \"value\" }\u003cbr /\u003e}\u003cbr /\u003e\u003c/pre\u003e | Matches on one or more querystring values, ignoring additional values |\n| \u003cpre\u003eWithExactQueryString(\"key=value\u0026other=value\")\u003cbr /\u003e\u003cbr /\u003eWithExactQueryString(new Dictionary\u0026lt;string,string\u003e\u003cbr /\u003e{\u003cbr /\u003e  { \"key\", \"value\" },\u003cbr /\u003e  { \"other\", \"value\" }\u003cbr /\u003e}\u003cbr /\u003e\u003c/pre\u003e | Matches on one or more querystring values, rejecting additional values |\n| \u003cpre\u003eWithFormData(\"key\", \"value\")\u003cbr /\u003e\u003cbr /\u003eWithFormData(\"key=value\u0026other=value\")\u003cbr /\u003e\u003cbr /\u003eWithFormData(new Dictionary\u0026lt;string,string\u003e\u003cbr /\u003e{\u003cbr /\u003e  { \"key\", \"value\" },\u003cbr /\u003e  { \"other\", \"value\" }\u003cbr /\u003e})\u003cbr /\u003e\u003c/pre\u003e | Matches on one or more form data values, ignoring additional values |\n| \u003cpre\u003eWithExactFormData(\"key=value\u0026other=value\")\u003cbr /\u003e\u003cbr /\u003eWithExactFormData(new Dictionary\u0026lt;string,string\u003e\u003cbr /\u003e{\u003cbr /\u003e  { \"key\", \"value\" },\u003cbr /\u003e  { \"other\", \"value\" }\u003cbr /\u003e})\u003cbr /\u003e\u003c/pre\u003e | Matches on one or more form data values, rejecting additional values |\n| \u003cpre\u003eWithContent(\"{'name':'McGee'}\")\u003c/pre\u003e | Matches on the (post) content of the request |\n| \u003cpre\u003eWithPartialContent(\"McGee\")\u003c/pre\u003e | Matches on the partial (post) content of the request |\n| \u003cpre\u003eWithHeaders(\"Authorization\", \"Basic abcdef\")\u003cbr /\u003e\u003cbr /\u003eWithHeaders(@\"Authorization: Basic abcdef\u003cbr /\u003eAccept: application/json\")\u003cbr /\u003e\u003cbr /\u003eWithHeaders(new Dictionary\u0026lt;string,string\u003e\u003cbr /\u003e{\u003cbr /\u003e  { \"Authorization\", \"Basic abcdef\" },\u003cbr /\u003e  { \"Accept\", \"application/json\" }\u003cbr /\u003e})\u003cbr /\u003e\u003c/pre\u003e | Matches on one or more HTTP header values |\n| \u003cpre\u003eWithJsonContent\u0026lt;T\u003e(new MyTypedRequest() [, jsonSerializerSettings])\u003cbr /\u003e\u003cbr /\u003eWithJsonContent\u0026lt;T\u003e(t =\u003e t.SomeProperty == 5 [, jsonSerializerSettings])\u003c/pre\u003e | Matches on requests that have matching JSON content |\n| \u003cpre\u003eWith(request =\u003e request.Content.Length \u003e 50)\u003c/pre\u003e | Applies custom matcher logic against an HttpRequestMessage |\n\nThese methods are chainable, making complex requirements easy to descirbe.\n\n### Verifying Matches\n\nWhen using Request Expectations via `Expect`, `MockHttpMessageHandler.VerifyNoOutstandingExpectation()` can be used to assert that there are no unmatched requests.\n\nFor 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 \ncan check how many unmatched requests there were.\n\n```csharp\nvar mockHttp = new MockHttpMessageHandler();\n\nvar request = mockHttp.When(\"http://localhost/api/user/*\")\n        .Respond(\"application/json\", \"{'name' : 'Test McGee'}\");\n\nvar client = mockHttp.ToHttpClient();\n\nawait client.GetAsync(\"http://localhost/api/user/1234\");\nawait client.GetAsync(\"http://localhost/api/user/2345\");\nawait client.GetAsync(\"http://localhost/api/user/3456\");\n\nConsole.Write(mockHttp.GetMatchCount(request)); // 3\n```\n\n### Match Behavior\n\nEach request is evaluated using the following process:\n\n1. 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\n2. If no Request Expectations exist, or the handler was constructed with `BackendDefinitionBehavior.Always`, the first matching Backend Definition processes the response\n3. `MockHttpMessageHandler.Fallback` handles the request\n\n### Fallback\n\nThe `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.\n\n```\n// Unhandled requests should throw an exception\nmockHttp.Fallback.Throw(new InvalidOperationException(\"No matching mock handler\"));\n\n// Unhandled requests should be executed against the network\nmockHttp.Fallback.Respond(new HttpClient());\n```\n\nThe default fallback behavior is to throw an exception that summarises why reach mocked request failed to match.\n\n### Examples\n\nThis example uses Expect to test an OAuth ticket recycle process:\n\n```csharp\n// Simulate an expired token\nmockHttp.Expect(\"/users/me\")\n        .WithQueryString(\"access_token\", \"old_token\")\n        .Respond(HttpStatusCode.Unauthorized);\n    \n// Expect the request to refresh the token and supply a new one\nmockHttp.Expect(\"/tokens/refresh\")\n        .WithFormData(\"refresh_token\", \"refresh_token\")\n        .Respond(\"application/json\", \"{'access_token' : 'new_token', 'refresh_token' : 'new_refresh'}\");\n    \n// Expect the original call to be retried with the new token\nmockHttp.Expect(\"/users/me\")\n        .WithQueryString(\"access_token\", \"new_token\")\n        .Respond(\"application/json\", \"{'name' : 'Test McGee'}\");\n    \nvar httpClient = mockHttp.ToHttpClient();\n\nvar userService = new UserService(httpClient);\n\nvar user = await userService.GetUserDetails();\n\nAssert.Equals(\"Test McGee\", user.Name);\nmockHttp.VerifyNoOutstandingExpectation();\n```\n\t\n## Platform Support\n\nMockHttp 7.0.0 and later are compiled for .NET 6, .NET 5, .NET Standard 2.0, .NET Standard 1.1\n\n[MockHttp 6.0.0](https://github.com/richardszalay/mockhttp/tree/v6.0.0#platform-support) has increased legacy platform support and can still be used, but is no longer updated with new features.\n\n## Build / Release\n\nClone the repository and build `RichardSzalay.MockHttp.sln` using MSBuild. NuGet package restore must be enabled.\n\nTo release, build:\n\n```\ndotnet pack -c Release --no-build ./RichardSzalay.MockHttp/RichardSzalay.MockHttp.csproj\n```\n\nIf you fork the project, simply rename the `nuspec` file accordingly and it will be picked up by the release script.\n\n## Contributors\n\nMany thanks to all the members of the community that have contributed PRs to this project:\n\n* [jozefizso](https://github.com/jozefizso)\n* [camiller2](https://github.com/camiller2)\n* [wislon](https://github.com/wislon)\n* [coryflucas](https://github.com/coryflucas)\n* [esskar](https://github.com/esskar)\n* [jericho](https://github.com/jericho)\n* [perfectsquircle](https://github.com/perfectsquircle)\n* [jr01](https://github.com/jr01)\n\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2023 Richard Szalay\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frichardszalay%2Fmockhttp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frichardszalay%2Fmockhttp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frichardszalay%2Fmockhttp/lists"}