wiremock-rs for Rust: Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

wiremock-rs: HTTP Mock Server for Rust

\n\n

In modern software development, testing is an integral part of the process. It can be particularly challenging to test code that interacts with external HTTP services. This is where the wiremock-rs library comes to the rescue — a powerful tool for creating HTTP mock servers in the Rust ecosystem.

\n\n

wiremock-rs provides the ability to emulate the behavior of external HTTP services, allowing developers to test their code in an isolated environment. Instead of sending real requests to external APIs (which can be slow, unreliable, or expensive), you can create a local mock server that responds exactly as you specify. This is especially useful when writing integration tests, testing error handling, and developing client libraries.

\n\n

The library is inspired by the popular Java tool WireMock but is completely rewritten in Rust, taking into account the idioms and features of the language. wiremock-rs supports all major capabilities: matching requests by URL, headers, body; returning various HTTP statuses; response delays; verifying call counts, and much more.

\n\n

Installation

\n\n

To install wiremock-rs, add the dependency to your Cargo.toml file:

\n\n
[dev-dependencies]\nwiremock = "0.6"
\n\n

Then run the command:

\n\n
cargo build
\n\n

Also, make sure you have Rust and Cargo installed. If not, install them via rustup.

\n\n

Quick Start

\n\n

Let's create a simple mock server that responds to GET requests:

\n\n
use wiremock::{MockServer, Mock, ResponseTemplate};\nuse wiremock::matchers::{method, path};\n\n#[tokio::main]\nasync fn main() {\n    // Start the mock server on a random port\n    let mock_server = MockServer::start().await;\n    \n    // Create a rule: on GET /hello respond with status 200 and body "Hello, World!"\n    let mock = Mock::given(method("GET"))\n        .and(path("/hello"))\n        .respond_with(ResponseTemplate::new(200)\n            .set_body_string("Hello, World!"));\n    \n    // Register the rule on the server\n    mock_server.register(mock).await;\n    \n    // Now you can make requests to the server\n    let client = reqwest::Client::new();\n    let response = client.get(&format!("{}/hello", &mock_server.uri()))\n        .send()\n        .await\n        .unwrap();\n    \n    println!("Status: {}", response.status());\n    println!("Body: {}", response.text().await.unwrap());\n    \n    // The server will stop automatically when main exits\n}
\n\n

This minimal example demonstrates the core idea: you start a server, define rules (matchers) and responses (response templates), and then register them. After that, your client code can make requests to the mock server.

\n\n

Main Methods and Functions

\n\n

1. MockServer::start()

\n

Signature: pub async fn start() -> MockServer

\n

Description: Starts a new mock server on a random available port. The server will run until the MockServer object is dropped.

\n
let server = MockServer::start().await;\nprintln!("Server started on {}", server.uri());
\n\n

2. MockServer::start_on_port(port: u16)

\n

Signature: pub async fn start_on_port(port: u16) -> MockServer

\n

Description: Starts the mock server on the specified port. Useful when a fixed port is needed for configuration.

\n
let server = MockServer::start_on_port(8080).await;\nassert_eq!(server.uri(), "http://127.0.0.1:8080");
\n\n

3. Mock::given(matcher: impl Matcher)

Recommendations