Skip to content

Request Matchers

This section describes matcher functions designed to target and match the scheme in incoming HTTP requests (such as http or https as in https://localhost:8080).

These matchers are especially useful when using the proxy and record-and-playback features of httpmock.

scheme

Specifies the scheme (e.g., “http” or “https”) that requests must match for the mock server to respond.

This method sets the scheme to filter requests and ensures that the mock server only matches requests with the specified scheme. This allows for more precise testing in environments where multiple protocols are used.

Note: Scheme matching is case-insensitive, conforming to RFC 3986, Section 3.2.2.

Example

use httpmock::prelude::*;
// Start a new mock server
let server = MockServer::start();
// Create a mock that only matches requests with the "http" scheme
let mock = server.mock(|when, then| {
when.scheme("http"); // Restrict to the "http" scheme
then.status(200); // Respond with status code 200 for all matched requests
});
// Make an "http" request to the server's URL to trigger the mock
let response = reqwest::blocking::get(server.url("/test")).unwrap();
// Ensure the request was successful
assert_eq!(response.status(), 200);
// Verify that the mock was called at least once
mock.assert();

Parameters

  • scheme: A string specifying the scheme that requests should match. Common values include “http” and “https”.

Returns

The modified When instance to allow for method chaining.

scheme_not

Specifies a scheme (e.g., “https”) that requests must not match for the mock server to respond.

This method allows you to exclude specific schemes from matching, ensuring that the mock server won’t respond to requests using those protocols. This is useful when you want to mock server behavior based on protocol security requirements or other criteria.

Note: Scheme matching is case-insensitive, conforming to RFC 3986, Section 3.2.2.

Example

use httpmock::prelude::*;
// Start a new mock server
let server = MockServer::start();
// Create a mock that will only match requests that do not use the "https" scheme
let mock = server.mock(|when, then| {
when.scheme_not("https"); // Exclude the "https" scheme from matching
then.status(200); // Respond with status code 200 for all matched requests
});
// Make a request to the server's URL with the "http" scheme to trigger the mock
let response = reqwest::blocking::get(server.url("/test")).unwrap();
// Ensure the request was successful
assert_eq!(response.status(), 200);
// Ensure that the mock was called at least once
mock.assert();

Parameters

  • scheme: A string specifying the scheme that requests should not match. Common values include “http” and “https”.

Returns

The modified When instance to allow for method chaining.