DEV.co
Open-Source Testing · richardszalay

mockhttp

MockHttp is a .NET testing library that replaces HttpClient's underlying handler with a mock, enabling developers to stub HTTP responses without network calls. It provides a fluent API for defining request matchers and responses, supporting both one-time expectations and reusable backend definitions.

Source: GitHub — github.com/richardszalay/mockhttp
1.8k
GitHub stars
91
Forks
C#
Primary language
MIT
License (OSI-approved)

Key facts

Objective fields from the source. Values we can't verify are shown as “Unknown” rather than guessed.

FieldValue
Repositoryrichardszalay/mockhttp
Ownerrichardszalay
Primary languageC#
LicenseMIT — OSI-approved
Stars1.8k
Forks91
Open issues17
Latest releasev7.0.0 (2023-10-12)
Last updated2026-07-02
Sourcehttps://github.com/richardszalay/mockhttp

What mockhttp is

MockHttp substitutes HttpMessageHandler with a custom implementation that intercepts HTTP requests and returns pre-configured responses based on URL, method, headers, query strings, form data, and JSON content matchers. It supports both expectation-driven (ordered, one-time) and backend-definition (unordered, reusable) matching patterns, with fallback handling for unmatched requests.

Quickstart

Get the mockhttp source

Clone the repository and explore it locally.

terminalbash
git clone https://github.com/richardszalay/mockhttp.gitcd mockhttp# follow the project's README for install & configuration

Need it deployed, integrated, or customized instead? DEV.co ships production installs.

Best use cases

Unit Testing Service Layers

Test application code that consumes HTTP APIs without external dependencies. MockHttp allows deterministic response control and verification of request construction (headers, parameters, body).

OAuth and Token Refresh Workflows

Verify multi-step authentication scenarios (e.g., token expiry → refresh → retry) using ordered expectations. The example in the README demonstrates this pattern.

Integration Tests for Microservices

Mock downstream HTTP dependencies in integration test suites to isolate service behavior and ensure contract compliance without running full external services.

Implementation considerations

  • Inject MockHttpMessageHandler into HttpClient or pass it to dependency injection; caller code remains unchanged.
  • Use Expect for ordered, single-match scenarios; use When for flexible, multi-match backend definitions. Mix both carefully—outstanding expectations block backend definitions.
  • Chain matchers (WithHeaders, WithQueryString, WithJsonContent, etc.) to specify precise request constraints; use fallback to catch unexpected requests.
  • Call VerifyNoOutstandingExpectation() to assert all expectations were consumed; use GetMatchCount() to validate interaction counts.
  • Configure fallback behavior: throw exceptions for unmatched requests (good for test isolation) or delegate to a real HttpClient (for passthrough).

When to avoid it — and what to weigh

  • Non-.NET Environments — MockHttp is C#/.NET-only. JavaScript, Python, Java, and other ecosystems require alternative solutions (e.g., nock, responses, WireMock).
  • Real Network Testing Required — If you need to validate actual DNS resolution, TLS handshakes, or network-level failures, MockHttp cannot help; use integration tests against real endpoints.
  • WebSocket or gRPC Communication — MockHttp targets HttpClient and HttpMessageHandler. WebSocket, gRPC, and other protocols require different mocking strategies.
  • Legacy Platforms Without .NET 6+ Support Needed — Latest version (7.0.0) targets .NET 6, .NET 5, and .NET Standard 2.0. Older platforms require v6.0.0, which is no longer updated with new features.

License & commercial use

Licensed under the MIT License, a permissive open-source license permitting commercial use, modification, and distribution with minimal restrictions (retain copyright notice and license text).

MIT License explicitly permits commercial use. No proprietary restrictions or licensing fees. Suitable for proprietary applications under standard MIT terms. Verify legal review aligns with your organization's OSI license acceptance policy.

DEV.co evaluation signals

Editorial assessment — not user reviews. Directional, with an explicit confidence level.

SignalAssessment
MaintenanceActive
DocumentationAdequate
License clarityClear
Deployment complexityLow
DEV.co fitGood
Assessment confidenceHigh
Security considerations

MockHttp is a testing utility, not a security layer. It does not perform encryption, authentication, or input validation. No sensitive data handling or cryptographic operations. Ensure test code containing mocked credentials (e.g., Bearer tokens) follows your organization's secret management practices. No known CVEs or disclosed vulnerabilities in recent releases; review recent issues for any security-related reports.

Alternatives to consider

Moq + IHttpClientFactory

Generic mocking library; requires more boilerplate to mock HttpMessageHandler. Less HTTP-specific API; often requires custom fixture code for request matching.

WireMock.Net

.NET alternative supporting HTTP request stubbing; starts a local HTTP server instead of in-process substitution. Better for contract testing and stateful scenarios; higher setup overhead.

NSubstitute + Custom Stubs

Lightweight, general-purpose mocking for .NET; requires manual HttpResponseMessage construction and matcher logic. Suitable only if you have minimal HTTP testing needs.

Software development agency

Build on mockhttp with DEV.co software developers

MockHttp streamlines unit test isolation for HTTP-dependent code. Start with the NuGet package and explore the fluent API—no external service setup required. Evaluate our custom development services if you need help integrating MockHttp into existing test suites or building complex mocking strategies.

Talk to DEV.co

Related open-source tools

Surfaced by semantic similarity across the DEV.co open-source index.

Related on DEV.co

Explore the category and the services that help you build with it.

mockhttp FAQ

Do I need to refactor my application code to use MockHttp?
No. MockHttp intercepts at the HttpMessageHandler level, the standard abstraction below HttpClient. Inject the mock handler during test setup; production code sees only HttpClient and remains unchanged.
Can MockHttp test real network conditions (timeouts, connection failures)?
Not directly. MockHttp returns synchronous mocked responses. To test timeout or fault handling, use Fallback.Respond(new HttpClient()) to delegate to a real endpoint, or use custom matchers with manually thrown exceptions (e.g., TaskCanceledException).
What's the difference between When and Expect?
When defines reusable backend definitions that can match multiple times in any order. Expect defines single-use request expectations that must match in the exact order specified. Use Expect for strict sequence validation; use When for flexible behavior.
Is MockHttp compatible with .NET Framework (non-Core)?
Version 7.0.0 targets .NET Standard 2.0, .NET 5, and .NET 6, which support .NET Framework 4.6.1+. Older platforms require v6.0.0, which has broader .NET Framework support but is no longer updated.

Work with a software development agency

Need help beyond evaluating mockhttp? DEV.co is a software development agency offering software development services and web development for teams of every size. Our software developers and web developers build custom software, web applications, APIs, and open-source testing integrations — and maintain them long-term.

Ready to Improve Your .NET API Testing?

MockHttp streamlines unit test isolation for HTTP-dependent code. Start with the NuGet package and explore the fluent API—no external service setup required. Evaluate our custom development services if you need help integrating MockHttp into existing test suites or building complex mocking strategies.