Skip to main content

Then

Struct Then 

Source
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

Source

pub fn status<U16: TryInto<u16>>(self, status: U16) -> Self
where <U16 as TryInto<u16>>::Error: Debug,

Configures the HTTP response status code that the mock server will return.

§Parameters
  • status: A u16 HTTP 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);
Source

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!");
Source

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!");
Source

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 a serde_json::Value object.
§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");
Source

pub fn json_body_obj<T>(self, body: &T) -> Self
where T: Serialize + ?Sized,

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 the serde::Serialize trait.
§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");
Source

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"
);
Source

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 a std::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);
Source

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);
Source

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 a Then instance 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 chain
Source

pub fn respond_with<F>(self, f: F) -> Self
where F: Fn(&HttpMockRequest) -> HttpMockResponse + Send + Sync + 'static,

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 the delay method.
  • 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).

Auto Trait Implementations§

§

impl Freeze for Then

§

impl RefUnwindSafe for Then

§

impl Send for Then

§

impl Sync for Then

§

impl Unpin for Then

§

impl UnsafeUnpin for Then

§

impl UnwindSafe for Then

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more