pub struct Then { /* private fields */ }Expand description
Represents the configuration of HTTP responses in a mock server environment.
The Then structure is used to define the details of the HTTP response that will be sent if
an incoming request meets the conditions specified by a corresponding When structure. It
allows for detailed customization of response aspects such as status codes, headers, body
content, and delays. This structure is integral to defining how the mock server behaves when
it receives a request that matches the defined expectations.
Implementations§
Source§impl Then
impl Then
Sourcepub fn status<U16: TryInto<u16>>(self, status: U16) -> Self
pub fn status<U16: TryInto<u16>>(self, status: U16) -> Self
Configures the HTTP response status code that the mock server will return.
§Parameters
status: Au16HTTP status code that the mock server should return for the configured request.
§Returns
Returns self to allow chaining of method calls on the Mock object.
§Example
Demonstrates setting a 200 OK status for a request to the path /hello.
use httpmock::prelude::*;
// Initialize the mock server
let server = MockServer::start();
// Configure the mock
let m = server.mock(|when, then| {
when.path("/hello");
then.status(200);
});
// Send a request and verify the response
let response = reqwest::blocking::get(server.url("/hello")).unwrap();
// Check that the mock was called as expected and the response status is as configured
m.assert();
assert_eq!(response.status(), 200);Sourcepub fn body<SliceRef: AsRef<[u8]>>(self, body: SliceRef) -> Self
pub fn body<SliceRef: AsRef<[u8]>>(self, body: SliceRef) -> Self
Configures the HTTP response body that the mock server will return.
§Parameters
body: The content of the response body, provided as a type that can be referenced as a byte slice.
§Returns
Returns self to allow chaining of method calls on the Mock object.
§Example
Demonstrates setting a response body for a request to the path /hello with a 200 OK status.
use httpmock::prelude::*;
use reqwest::blocking::Client;
// Initialize the mock server
let server = MockServer::start();
// Configure the mock
let m = server.mock(|when, then| {
when.path("/hello");
then.status(200)
.body("ohi!");
});
// Send a request and verify the response
let response = Client::new()
.get(server.url("/hello"))
.send()
.unwrap();
// Check that the mock was called as expected and the response body is as configured
m.assert();
assert_eq!(response.status(), 200);
assert_eq!(response.text().unwrap(), "ohi!");Sourcepub fn body_from_file<IntoString: Into<String>>(
self,
resource_file_path: IntoString,
) -> Self
pub fn body_from_file<IntoString: Into<String>>( self, resource_file_path: IntoString, ) -> Self
Configures the HTTP response body with content loaded from a specified file on the mock server.
§Parameters
resource_file_path: A string representing the path to the file whose contents will be used as the response body. The path can be absolute or relative to the server’s running directory.
§Returns
Returns self to allow chaining of method calls on the Mock object.
§Panics
Panics if the specified file cannot be read, or if the path provided cannot be resolved to an absolute path.
§Example
Demonstrates setting the response body from a file for a request to the path /hello with a 200 OK status.
use httpmock::prelude::*;
use reqwest::blocking::Client;
// Initialize the mock server
let server = MockServer::start();
// Configure the mock
let m = server.mock(|when, then| {
when.path("/hello");
then.status(200)
.body_from_file("tests/resources/simple_body.txt");
});
// Send a request and verify the response
let response = Client::new()
.get(server.url("/hello"))
.send()
.unwrap();
// Check that the mock was called as expected and the response body matches the file contents
m.assert();
assert_eq!(response.status(), 200);
assert_eq!(response.text().unwrap(), "ohi!");Sourcepub fn json_body<V: Into<Value>>(self, body: V) -> Self
pub fn json_body<V: Into<Value>>(self, body: V) -> Self
Sets the JSON body for the HTTP response that will be returned by the mock server.
This function accepts a JSON object that must be serializable and deserializable by serde. Note that this method does not automatically set the “Content-Type” header to “application/json”. You will need to set this header manually if required.
§Parameters
body: The HTTP response body in the form of aserde_json::Valueobject.
§Returns
Returns self to allow chaining of method calls on the Mock object.
§Example
Demonstrates how to set a JSON body and a matching “Content-Type” header for a mock response.
use httpmock::prelude::*;
use serde_json::{Value, json};
use reqwest::blocking::Client;
// Arrange
tracing_subscriber::fmt::init();
let server = MockServer::start();
// Configure the mock
let m = server.mock(|when, then| {
when.path("/user");
then.status(200)
.header("content-type", "application/json")
.json_body(json!({ "name": "Hans" }));
});
// Act
let response = Client::new()
.get(server.url("/user"))
.send()
.unwrap();
// Get the status code first
let status = response.status();
// Extract the text from the response
let response_text = response.text().unwrap();
// Deserialize the JSON response
let user: Value =
serde_json::from_str(&response_text).expect("cannot deserialize JSON");
// Assert
m.assert();
assert_eq!(status, 200);
assert_eq!(user["name"], "Hans");Sourcepub fn json_body_obj<T>(self, body: &T) -> Self
pub fn json_body_obj<T>(self, body: &T) -> Self
Sets the JSON body that will be returned by the mock server using a serializable serde object.
This method converts the provided object into a JSON string. It does not automatically set the “Content-Type” header to “application/json”, so you must set this header manually if it’s needed.
§Parameters
body: A reference to an object that implements theserde::Serializetrait.
§Returns
Returns self to allow chaining of method calls on the Mock object.
§Panics
Panics if the object cannot be serialized into a JSON string.
§Example
Demonstrates setting a JSON body and the corresponding “Content-Type” header for a user object.
use httpmock::prelude::*;
use reqwest::blocking::Client;
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct TestUser {
name: String,
}
// Arrange
tracing_subscriber::fmt::init();
let server = MockServer::start();
// Configure the mock
let m = server.mock(|when, then| {
when.path("/user");
then.status(200)
.header("content-type", "application/json")
.json_body_obj(&TestUser {
name: String::from("Hans"),
});
});
// Act
let response = Client::new()
.get(server.url("/user"))
.send()
.unwrap();
// Get the status code first
let status = response.status();
// Extract the text from the response
let response_text = response.text().unwrap();
// Deserialize the JSON response into a TestUser object
let user: TestUser =
serde_json::from_str(&response_text).unwrap();
// Assert
m.assert();
assert_eq!(status, 200);
assert_eq!(user.name, "Hans");Sourcepub fn header<KeyString: Into<String>, ValueString: Into<String>>(
self,
name: KeyString,
value: ValueString,
) -> Self
pub fn header<KeyString: Into<String>, ValueString: Into<String>>( self, name: KeyString, value: ValueString, ) -> Self
Sets an HTTP header that the mock server will return in the response.
This method configures a response header to be included when the mock server handles a request.
§Parameters
name: The name of the header to set.value: The value of the header.
§Returns
Returns self to allow chaining of method calls on the Mock object.
§Example
Demonstrates setting the “Expires” header for a response to a request to the root path.
use httpmock::prelude::*;
use reqwest::blocking::Client;
// Arrange
tracing_subscriber::fmt::init();
let server = MockServer::start();
// Configure the mock
let m = server.mock(|when, then| {
when.path("/");
then.status(200)
.header("Expires", "Wed, 21 Oct 2050 07:28:00 GMT");
});
// Act
let response = Client::new()
.get(server.url("/"))
.send()
.unwrap();
// Assert
m.assert();
assert_eq!(response.status(), 200);
assert_eq!(
response.headers().get("Expires").unwrap().to_str().unwrap(),
"Wed, 21 Oct 2050 07:28:00 GMT"
);Sourcepub fn delay<D: Into<Duration>>(self, duration: D) -> Self
pub fn delay<D: Into<Duration>>(self, duration: D) -> Self
Sets a delay for the mock server response.
This method configures the server to wait for a specified duration before sending a response, which can be useful for testing timeout scenarios or asynchronous operations.
§Parameters
duration: The length of the delay as astd::time::Duration.
§Returns
Returns self to allow chaining of method calls on the Mock object.
§Panics
Panics if the specified duration results in a delay that cannot be represented as a 64-bit unsigned integer of milliseconds (more than approximately 584 million years).
§Example
Demonstrates setting a 3-second delay for a request to the path /delay.
use std::time::{SystemTime, Duration};
use httpmock::prelude::*;
use reqwest::blocking::Client;
// Arrange
tracing_subscriber::fmt::init();
let start_time = SystemTime::now();
let three_seconds = Duration::from_secs(3);
let server = MockServer::start();
// Configure the mock
let mock = server.mock(|when, then| {
when.path("/delay");
then.status(200)
.delay(three_seconds);
});
// Act
let response = Client::new()
.get(server.url("/delay"))
.send()
.unwrap();
// Assert
mock.assert();
assert!(start_time.elapsed().unwrap() >= three_seconds);Sourcepub fn up_to_n_times(self, n: usize) -> Self
pub fn up_to_n_times(self, n: usize) -> Self
Limits the mock to serving up to n calls.
Once the mock has served n calls, it stops matching and later requests fall through to
other mocks. Mocks are matched in the order they were created, so create the limited mock
first. This is useful when the code under test retries a request on its own and you cannot
call Mock::delete between attempts.
Serving fewer than n calls does not fail the test. The mock stays registered after it
stops matching, and Mock::calls and
Mock::assert_calls still work.
§Parameters
n: The number of calls the mock serves before it stops matching. Must be greater than zero.
§Returns
Returns self to allow chaining of method calls on the Then object.
§Panics
Creating the mock panics if n is zero, or if the mock server is a remote server that
predates this method.
§Example
Demonstrates an endpoint that fails twice before a second mock takes over.
use httpmock::prelude::*;
use reqwest::blocking::get;
// Arrange
let server = MockServer::start();
let failing = server.mock(|when, then| {
when.path("/health");
then.status(503).up_to_n_times(2);
});
let healthy = server.mock(|when, then| {
when.path("/health");
then.status(200);
});
// Act
let statuses: Vec<u16> = (0..3)
.map(|_| get(server.url("/health")).unwrap().status().as_u16())
.collect();
// Assert
assert_eq!(statuses, vec![503, 503, 200]);
failing.assert_calls(2);
healthy.assert_calls(1);Sourcepub fn and(self, func: impl FnOnce(Then) -> Then) -> Self
pub fn and(self, func: impl FnOnce(Then) -> Then) -> Self
Applies a custom function to modify a Then instance, enhancing flexibility and readability
in setting up mock server responses.
This method allows you to encapsulate complex configurations into reusable functions,
and apply them without breaking the chain of method calls on a Then object.
§Parameters
func: A function that takes aTheninstance and returns it after applying some modifications.
§Returns
Returns self to allow chaining of method calls on the Then object.
§Example
Demonstrates how to use the and method to maintain readability while applying multiple
modifications from an external function.
use std::time::Duration;
use http::{StatusCode, header::HeaderValue};
use httpmock::{Then, MockServer};
// Function that configures a response with JSON content and a delay
fn ok_json_with_delay(then: Then) -> Then {
then.status(StatusCode::OK.as_u16())
.header("content-type", "application/json")
.delay(Duration::from_secs_f32(0.5))
}
// Usage within a method chain
let server = MockServer::start();
let then = server.mock(|when, then| {
when.path("/example");
then.header("general-vibe", "much better")
.and(ok_json_with_delay);
});
// The `and` method keeps the setup intuitively readable as a continuous chainSourcepub fn respond_with<F>(self, f: F) -> Self
pub fn respond_with<F>(self, f: F) -> Self
Sets a dynamic responder that is invoked for every request matching the when
conditions. The provided closure receives the full HttpMockRequest and must
fully determine the HttpMockResponse (status, headers, and body).
This is ideal when the reply depends on request details (path, headers, body), or when you need stateful behavior across calls (e.g., counters, cycling codes).
Important: Dynamic responders are only supported by the local server. They are not supported by remote/standalone servers and this method will panic when used against them.
§Parameters
f: A response generator closure that is executed on the mock server’s request handling thread for each match.
§Behavior
- When set, this responder overrides any static configuration on
Then(e.g., previously set status/body/headers) for matching requests other than the configured delay using thedelaymethod. - The closure may capture shared state. If you mutate shared data, use a
synchronization primitive (
Mutex,RwLock, or atomics). This is required because the responder runs on the mock server’s request-handling thread, which is distinct from the test thread.
§Returns
Returns self for continued method chaining on Then.
§Example
A minimal dynamic responder that mirrors the request body value back to the client:
use httpmock::{MockServer, HttpMockRequest, HttpMockResponse};
use reqwest::blocking::Client;
let server = MockServer::start();
let mock = server.mock(|when, then| {
when.path("/echo");
then.respond_with(|req: &HttpMockRequest| {
// Echo the received request body back in the response body.
let echoed_body = req.body().to_string();
HttpMockResponse::builder()
.status(200)
.body(echoed_body)
.build()
});
});
let res = Client::new()
.post(format!("{}/echo", server.base_url()))
.body("Hello, world!")
.send()
.unwrap();
mock.assert();
assert_eq!(res.status(), 200);
assert_eq!(res.text().unwrap(), "Hello, world!");§Example
Stateful dynamic responder that increments the status code on each call:
use httpmock::{MockServer, HttpMockRequest, HttpMockResponse};
use reqwest::blocking::Client;
use std::sync::Mutex;
// Arrange
let server = MockServer::start();
// Shared counter used inside the responder closure.
// Use a Mutex/RwLock/atomic because the closure runs on the server thread.
let call_count = Mutex::new(0);
let mock = server.mock(|when, then| {
when.path("/hello");
then.respond_with(move |_req: &HttpMockRequest| {
let mut count = call_count.lock().unwrap();
*count += 1;
HttpMockResponse::builder()
.status(200 + *count) // 201, 202, 203, ...
.build()
});
});
// Act
let client = Client::new();
let response1 = client.get(format!("{}/hello", server.base_url())).send().unwrap();
let response2 = client.get(format!("{}/hello", server.base_url())).send().unwrap();
let response3 = client.get(format!("{}/hello", server.base_url())).send().unwrap();
// Assert
mock.assert_calls(3);
assert_eq!(response1.status(), 201);
assert_eq!(response2.status(), 202);
assert_eq!(response3.status(), 203);§HTTP Crate Integration
Both HttpMockRequest and HttpMockResponse implement conversion traits
to and from types of the http crate.
This means you can seamlessly integrate with other HTTP utilities or middleware
that operate on http::Request and http::Response.
use httpmock::{MockServer, HttpMockRequest, HttpMockResponse};
use reqwest::blocking::Client;
let server = MockServer::start();
let mock = server.mock(|when, then| {
when.method("POST").path("/echo");
then.respond_with(|req: &HttpMockRequest| {
// Convert the HttpMockRequest to an `http` crate Request (with body)
let http_req: http::Request<String> = req.into();
// Build an `http` crate Response (auto-converted to HttpMockResponse)
http::Response::builder()
.status(200)
.header("content-type", "text/plain")
.body(format!("Echo from {}: {}", http_req.uri().path(), http_req.body()))
.unwrap()
.into()
});
});
let res = Client::new()
.post(format!("{}/echo", server.base_url()))
.body("Hello from client!")
.send()
.unwrap();
mock.assert();
assert_eq!(res.status(), 200);
assert_eq!(res.text().unwrap(), "Echo from /echo: Hello from client!");§Notes
- Avoid long-running or blocking work inside the responder; it runs on the request handling path and will delay responses.
- If you need to combine static defaults with dynamic tweaks, compute them inside
the closure (e.g., start from
HttpMockResponse::builder()and adjust as needed).