Skip to content

Playback

After creating a recording, you can replay it by loading it into a mock server instance using the httpmock Rust API as follows:

// ...
// Save the recording to
// "target/httpmock/recordings/github-torvalds-scenario_<timestamp>.yaml".
let target_path = recording
.save("github-torvalds-scenario")
.expect("cannot store scenario on disk");
let playback_server = MockServer::start();
// Play back the recorded interactions from the file.
playback_server.playback(target_path);

After calling MockServer::playback, the recording will be loaded into the mock server. This allows all previously recorded requests to act as matching criteria, similar to how you configure normal mocks using MockServer::mock with the When structure.

Hereafter, whenever the mock server receives a request that matches any of the recorded requests, it will respond with the corresponding recorded response.

Full Example

The following example demonstrates how you can use the forwarding feature to record and playback requests sent to the GitHub API and the responses it returns.

#[cfg(all(feature = "proxy", feature = "record"))]
#[test]
fn playback_github_api() {
// Start a mock server for the test
let server = MockServer::start();
// Configure the mock server to forward requests to the target
// host (GitHub API) instead of responding with a mock. The 'rule'
// parameter allows you to define conditions under which forwarding
// should occur.
server.forward_to("https://api.github.com", |rule| {
rule.filter(|when| {
when.any_request(); // Forward all requests.
});
});
// Set up recording to capture all forwarded requests and responses
let recording = server.record(|rule| {
rule.filter(|when| {
when.any_request(); // Record all requests and responses.
});
});
// Send an HTTP request to the mock server, which will be forwarded
// to the GitHub API
let client = Client::new();
let response = client
.get(server.url("/repos/torvalds/linux"))
// GitHub requires a User-Agent header
.header("User-Agent", "httpmock-test")
.send()
.unwrap();
// Assert that the response from the forwarded request is as expected
assert_eq!(response.status().as_u16(), 200);
assert!(response.text().unwrap().contains("\"private\":false"));
// Save the recorded interactions to a file
let target_path = recording
.save("github-torvalds-scenario")
.expect("Failed to save the recording to disk");
// Start a new mock server instance for playback
let playback_server = MockServer::start();
// Load the recorded interactions into the new mock server
playback_server.playback(target_path);
// Send a request to the playback server and verify the response
// matches the recorded data
let response = client
.get(playback_server.url("/repos/torvalds/linux"))
.send()
.unwrap();
assert_eq!(response.status().as_u16(), 200);
assert!(response.text().unwrap().contains("\"private\":false"));
}