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
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");Sourcepub fn json_body_obj<T: Serialize>(self, body: &T) -> Self
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 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
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");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
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"
);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
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);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 chain