Skip to content

Method

This section describes matcher functions designed to target and match the method in incoming HTTP requests, such as GET, POST, etc.

method

Sets the expected HTTP method for which the mock server should respond.

This method ensures that the mock server only matches requests that use the specified HTTP method, such as GET, POST, or any other valid method. This allows testing behavior that’s specific to different types of HTTP requests.

Note: Method matching is case-insensitive.

Example

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

Parameters

  • method: An HTTP method as either a Method enum or a String value, specifying the expected method type for matching.

Returns

The updated When instance to allow for method chaining.

method_not

Excludes the specified HTTP method from the requests the mock server will respond to.

This method ensures that the mock server does not respond to requests using the given HTTP method, like GET, POST, etc. This allows testing scenarios where a particular method should not trigger a response, and thus testing behaviors like method-based security.

Note: Method matching is case-insensitive.

Example

use httpmock::prelude::*;
// Start a new mock server
let server = MockServer::start();
// Create a mock that matches any request except those using the `POST` method
let mock = server.mock(|when, then| {
when.method_not(POST); // Exclude the `POST` HTTP method from matching
then.status(200); // Respond with status code 200 for all other matched requests
});
// Make a GET request to the server's URL, which will trigger the mock
let response = reqwest::blocking::get(server.url("/")).unwrap();
// Ensure the request was successful
assert_eq!(response.status(), 200);
// Ensure that the mock was called at least once
mock.assert();

Parameters

  • method: An HTTP method as either a Method enum or a String value, specifying the method type to exclude from matching.

Returns

The updated When instance to allow for method chaining.