MockExt

Trait MockExt 

Source
pub trait MockExt<'a> {
    // Required methods
    fn new(id: usize, mock_server: &'a MockServer) -> Mock<'a>;
    fn id(&self) -> usize;
}
Expand description

The MockExt trait extends the Mock structure with some additional functionality, that is usually not required.

Required Methods§

Source

fn new(id: usize, mock_server: &'a MockServer) -> Mock<'a>

Creates a new Mock instance that references an already existing mock on a MockServer. This method is typically used in advanced scenarios where you need to re-establish a reference to a mock after its original instance has been dropped or lost.

§Parameters
  • id - The ID of the existing mock on the MockServer.
  • mock_server - A reference to the MockServer where the mock is hosted.
§Example

Demonstrates how to recreate a Mock instance from a mock ID to verify assertions or perform further actions after the original Mock reference has been discarded.

use httpmock::{MockServer, Mock, MockExt};
use reqwest::blocking::get;

// Arrange
let server = MockServer::start();
let initial_mock = server.mock(|when, then| {
    when.path("/test");
    then.status(202);
});

// Store away the mock ID and drop the initial Mock instance
let mock_id = initial_mock.id();
drop(initial_mock);

// Act: Send an HTTP request to the mock endpoint
let response = get(&server.url("/test")).unwrap();

// Recreate the Mock instance using the stored ID
let recreated_mock = Mock::new(mock_id, &server);

// Assert: Use the recreated Mock to check assertions
recreated_mock.assert();
assert_eq!(response.status(), 202);

For more detailed use cases, see Issue 26 on GitHub.

Source

fn id(&self) -> usize

Returns the unique identifier (ID) assigned to the mock on the MockServer. This ID is used internally by the mock server to track and manage the mock throughout its lifecycle.

The ID can be particularly useful in advanced testing scenarios where mocks need to be referenced or manipulated programmatically after their creation.

§Returns

Returns the ID of the mock as a usize.

§Example

Demonstrates how to retrieve the ID of a mock for later reference or manipulation.

use httpmock::MockExt;
use httpmock::prelude::*;

// Arrange: Start a mock server and create a mock
let server = MockServer::start();
let mock = server.mock(|when, then| {
    when.path("/example");
    then.status(200);
});

// Act: Retrieve the ID of the mock
let mock_id = mock.id();

// The mock_id can now be used to reference or manipulate this specific mock in subsequent operations
println!("Mock ID: {}", mock_id);

This method is particularly useful when dealing with multiple mocks and needing to assert or modify specific mocks based on their identifiers.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<'a> MockExt<'a> for Mock<'a>