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
let _ = env_logger::try_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: Serialize>(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 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
let _ = env_logger::try_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
let _ = env_logger::try_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
let _ = env_logger::try_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 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

Auto Trait Implementations§

§

impl Freeze for Then

§

impl !RefUnwindSafe for Then

§

impl !Send for Then

§

impl !Sync for Then

§

impl Unpin 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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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
Source§

impl<T> ErasedDestructor for T
where T: 'static,