Every Rust test suite eventually hits the same wall: the function you want to test calls a payment API, a database, and a clock. You cannot run those in CI, so you mock them — and then you discover that the Rust ecosystem splits mocking into two completely different activities that people confusingly call by the same name.
Trait mocking replaces an interface with a generated implementation that records calls and returns canned values. HTTP mocking starts a real server on a random port and lets your HTTP client talk to it. They solve different problems, and the three main crates — mockall, wiremock, and mockito — are not interchangeable.
Here is the breakdown, with code pulled from each project’s current repository and the maintenance data that actually predicts which one you will still be using in two years.
The Short Answer
Use mockall for traits and wiremock for HTTP. mockall (0.15.0, 1,853 stars, last commit November 2026) is the most capable trait-mocking crate in the ecosystem and the only one with proper expectation syntax — .with(), .times(), .returning(), call sequences. wiremock (0.6.5, 803 stars) is the better HTTP mock server because it runs on both tokio and async-std, gives each test an isolated server, and supports request matching on body and headers. Choose mockito (1.7.2, 788 stars) if you want a smaller, synchronous-friendly API with excellent failure diffs and do not need async-std support.
One thing to internalize before the tables: mocking a trait you own is a design decision, mocking an HTTP boundary is a testing convenience. Over-mocking traits is how Rust test suites become refactoring obstacles.
How the Three Compare
| Dimension | mockall | wiremock | mockito |
|---|---|---|---|
| GitHub stars | 1,853 | 803 | 788 |
| Last commit | Nov 23, 2026 | Aug 24, 2025 | Aug 1, 2026 |
| Current version | 0.15.0 | 0.6.5 | 1.7.2 |
| License | Apache-2.0 | Apache-2.0 | MIT |
| What it mocks | Traits, structs, modules | HTTP servers | HTTP servers |
| Async runtime | Runtime-agnostic | tokio and async-std | Runtime-agnostic |
| Expectation API | .with(), .times(), .returning(), sequences | Mock::given(matchers) | server.mock(method, path) |
| Request matching | N/A | Method, path, query, headers, body, custom | Method, path, query, headers, body |
| Failure diagnostics | Panics on unmet expectations | 404 on unmatched request | Colored diff of unmatched request |
| Isolation per test | Per-mock instance | MockServer::start() per test | Server::new() per test |
| Learning curve | Steep (macros, predicates) | Moderate | Low |
The important split in that table is rows 6 through 9: mockall is a compile-time code generator, wiremock and mockito are runtime servers. That is why mockall can verify “this method was called exactly twice with argument 4” and wiremock cannot verify anything except which requests arrived.
Which One Fits Your Test
| Your situation | Use | Why |
|---|---|---|
| Service depends on a trait (repository, clock, mailer) | mockall | Generates a mock struct from the trait; expectations are checked at drop |
| Code calls a third-party HTTP API | wiremock | Real socket, real client, no trait indirection |
| Testing a client you wrote against a flaky vendor | wiremock or mockito | Record the vendor’s response shape, assert your parsing |
Test suite already uses async-std | wiremock | mockito and mockall’s async support assume tokio-style runtimes |
| You want readable failure output above all | mockito | Colored diff of expected vs actual request |
| Verifying call counts and argument order | mockall | Only crate with first-class sequence and count expectations |
| Mocking a database driver | Neither | Use a test container or an in-memory database instead |
mockall: Trait Mocking With Real Expectations
mockall generates a mock struct from a trait with one attribute. From the repository README:
| |
What makes this more than a stub generator is the expectation layer. You can demand exact call counts, match arguments with predicates (eq, function, predicate!), return different values on successive calls, and assert ordering with Sequence. Mockall also verifies expectations in Drop, so a test that never calls the mocked method fails instead of silently passing.
The cost is compile time and ergonomics. Every #[automock] expands into a struct with a method per trait method, and async traits produce noticeably more generated code. Generic traits, associated types, and lifetimes all work but require reading the docs on mock! — the macro form that mocks a trait you do not own:
| |
That is the escape hatch for wrapping third-party traits. For traits in your own crate, #[automock] is almost always enough.
When not to use it: mocking your own domain traits to test business logic. If a service needs six mocks to test one function, the function has six dependencies and the test is telling you something about the design, not about the mocks.
wiremock: A Real HTTP Server Per Test
wiremock runs an actual HTTP server bound to a random local port, then mounts mocks on it. Your production code uses its real HTTP client, which means the test exercises serialization, headers, timeouts, and error mapping — everything a trait mock would skip.
| |
Two design details matter more than the syntax. First, MockServer::start() finds a free port and the server is fully isolated, so tests can run in parallel without port collisions — a problem that plagues hand-rolled mock servers in other ecosystems. Second, unmatched requests return 404 by default, which means an accidental endpoint call fails loudly instead of hitting the network.
The matcher set is broad: method, path, query_param, header, body_json, and body_string can be combined with .and(). For responses, ResponseTemplate supports status, headers, JSON bodies, and delays — the delay support is genuinely useful for testing timeout handling without sleeping in your test.
Where wiremock shows its age is release cadence: the last commit was August 2025. The API is stable and the crate works, but do not expect brand-new features.
mockito: Small, Synchronous, Great Diffs
mockito takes the same server-based approach with a fraction of the API surface:
| |
The mock.assert() call is the differentiator in daily use: when a request does not match, mockito prints a colored diff of the last unmatched request against what the mock expected. In a test suite with twenty HTTP interactions, that diff is the difference between a five-second fix and a twenty-minute hunt.

mockito also works without an async runtime, which makes it the natural choice for testing synchronous clients or for codebases that deliberately avoid pulling tokio into dev-dependencies. The trade-off is that it does not support async-std, and its matcher vocabulary is smaller than wiremock’s.
The Pitfalls That Make Mocked Tests Useless
1. Over-specification is the number one cause of brittle suites. mock.expect_foo().with(eq(4)).times(1) asserts that your code calls foo(4) exactly once. That is a test of implementation, not behavior. The moment you refactor to call foo(5) for a legitimate reason, the test fails even though the behavior is correct. Prefer .returning() with loose matchers, and reserve strict expectations for contracts you genuinely care about — payment calls, audit writes, idempotency keys.
2. Never mock what you do not own. Wrapping a third-party crate’s trait in mock!{} couples your tests to their API. Wrap it in your own thin adapter trait, mock the adapter, and let one integration test cover the real client against wiremock.
3. Async mocks and Send bounds. mockall generates mocks that must satisfy your trait’s bounds. Async traits returning impl Future + Send sometimes require explicit #[automock] tuning or the mock! form; the error messages point at generated code and are hard to read. Test one trait at a time when adding mocks to an existing codebase.
4. Mocked databases hide migration bugs. If your repository layer is mocked in every test, nothing verifies that your SQL still matches your schema. Keep a small set of integration tests against a real Postgres — the Rust database libraries comparison covers the driver choices that make those tests cheap to run.
5. Error paths deserve mocks more than happy paths. The valuable test is “the vendor returns 503 and we retry twice,” not “the vendor returns 200.” wiremock’s ResponseTemplate with a delay plus a 503 is three lines and tests the branch that actually pages you at 3 a.m. If your error types are messy, the anyhow vs thiserror vs eyre guide will make the assertions cleaner.
6. Keep mocks out of the public API. #[cfg_attr(test, automock)] is the right pattern precisely because the generated MockMyTrait exists only in test builds. Do not export mocks as a feature flag for downstream crates — you will end up maintaining two versions of every trait.
For teams testing scrapers and HTTP-heavy clients specifically, the Rust web scraping libraries comparison shows where mock servers stop being sufficient and a recorded-fixture approach wins instead.
FAQ
What is the difference between mockall and wiremock?
mockall generates mock implementations of Rust traits at compile time and verifies call expectations. wiremock starts a real local HTTP server and returns canned responses to your HTTP client. Use mockall for internal interfaces you own, and wiremock for HTTP boundaries you do not control.
Can I use mockall and wiremock together?
Yes, and mature codebases usually do. mockall replaces your repository and clock traits, while wiremock intercepts the outbound HTTP calls your service makes. They do not conflict because they operate at different layers — one replaces a type, the other replaces a network endpoint.
Is mockito better than wiremock?
It depends on what you value. mockito has simpler syntax, works without an async runtime, and produces better failure diffs. wiremock supports both tokio and async-std, has more matchers, and is the more common choice in async-first codebases. Neither is objectively better.
How do I mock an async trait in Rust?
Use #[cfg_attr(test, automock)] on the trait and let mockall generate the async mock; in most cases the generated code satisfies Send bounds automatically. If the compiler complains about impl Future + Send, use the mock! macro form and specify the return type explicitly, or return a boxed future from the trait.
Should I mock the database in unit tests?
No, not exclusively. Mock the repository trait for fast unit tests of business logic, but keep at least one integration test per repository against a real database (a container or a local instance). Mocked repositories cannot catch schema drift, broken SQL, or transaction isolation mistakes.
Why does my mockall test fail even though the code works?
The most common cause is an unmet expectation: times(1) when the code called the method twice, or .with(eq(x)) when the actual argument differed slightly. Mockall panics in Drop when expectations are unmet, so the failure appears at the end of the test rather than at the call site. Check the panic message for the expectation index.
💰 想测试你的市场判断力?我用 Polymarket 做预测市场交易——这是全球最大的预测市场平台,从大选结果到技术监管时间线,什么都可以押注。和赌博不同,这是真正的信息市场:你懂的信息越多,胜率越高。我靠预测技术相关事件的走向已经赚了不少。用我的邀请链接注册:Polymarket.com