Skip to content

Body

This section explains functions designed to set values in the response when a request meets all specified criteria.

status

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

body

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

body_from_file

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

json_body

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

json_body_obj

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

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