Mock

Struct Mock 

Source
pub struct Mock<'a> {
    pub id: usize,
    /* private fields */
}
Expand description

Provides a reference to a mock configuration stored on a MockServer. This structure is used for interacting with, monitoring, and managing a specific mock’s lifecycle, such as observing call counts or removing the mock from the server.

This reference allows you to control and verify the behavior of the server in response to incoming HTTP requests that match the mock criteria.

§Example

Demonstrates how to create and manipulate a mock on the server. This includes monitoring its usage and effectively managing its lifecycle by removing it when necessary.

use httpmock::prelude::*;
use reqwest::blocking::get;

// Arrange
let server = MockServer::start();

// Create and configure a mock
let mut mock = server.mock(|when, then| {
   when.path("/test");
   then.status(202);
});

// Act by sending a request and verifying the mock's hit count
let response1 = get(&server.url("/test")).unwrap();
assert_eq!(mock.hits(), 1); // Verify the mock was triggered

// Remove the mock and test the server's response to the same path again
mock.delete();
let response2 = get(&server.url("/test")).unwrap();

// Assert
assert_eq!(response1.status(), 202);
assert_eq!(response2.status(), 404); // Expect a 404 status after the mock is deleted

Fields§

§id: usize

Implementations§

Source§

impl<'a> Mock<'a>

Source

pub fn new(id: usize, server: &'a MockServer) -> Self

Source

pub fn assert(&self)

Verifies that the mock server received exactly one HTTP request matching all specified request conditions for this mock. This method is useful for confirming that a particular operation interacts with the server as expected in test scenarios.

Attention: To assert receipt of multiple requests, use Mock::assert_hits or Mock::hits methods instead.

§Example

Demonstrates creating a mock to match a specific request path, sending a request to that path, and then verifying that exactly one such request was received.

use httpmock::prelude::*;
use reqwest::blocking::get;

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

// Act: Send a request to the specified path
get(&server.url("/hits")).unwrap();

// Assert: Check that the server received exactly one request that matched the mock
mock.assert();
§Panics

This method will panic if the mock server did not receive exactly one matching request or if there are issues with the mock server’s availability.

Source

pub async fn assert_async(&self)

Asynchronously verifies that the mock server received exactly one HTTP request matching all specified request conditions for this mock. This method is suited for asynchronous testing environments where operations against the mock server occur non-blockingly.

Attention: To assert the receipt of multiple requests asynchronously, consider using Mock::assert_hits_async or Mock::hits_async.

§Example

Demonstrates setting up an asynchronous mock, sending a request, and verifying that exactly one such request was received.

use httpmock::prelude::*;
use reqwest::get;
use syn::token;

let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
    // Arrange: Start a mock server asynchronously and set up a mock
    let server = MockServer::start_async().await;
    let mut mock = server.mock_async(|when, then| {
        when.path("/hits");
        then.status(200);
    }).await;

    // Act: Send a request to the specified path asynchronously
    get(&server.url("/hits")).await.unwrap();

    // Assert: Check that the server received exactly one request that matched the mock
    mock.assert_async().await;
});
§Panics

This method will panic if the mock server did not receive exactly one matching request or if there are issues with the mock server’s availability.

Source

pub fn assert_hits(&self, hits: usize)

👎Deprecated since 0.8.0: please use assert_calls instead

Verifies that the mock server received the specified number of HTTP requests matching all the request conditions defined for this mock.

This method is useful for confirming that a series of operations interact with the server as expected within test scenarios, especially when specific interaction counts are significant.

Attention: Use Mock::assert for the common case of asserting exactly one hit.

§Example

Demonstrates creating a mock, sending multiple requests, and verifying the number of received requests matches expectations.

use httpmock::prelude::*;
use reqwest::blocking::get;

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

// Act: Send multiple requests to the configured path
get(&server.url("/hits")).unwrap();
get(&server.url("/hits")).unwrap();

// Assert: Check that the server received exactly two requests that matched the mock
mock.assert_hits(2);
§Panics

This method will panic if the actual number of hits differs from the specified hits, or if there are issues with the mock server’s availability.

Source

pub fn assert_calls(&self, count: usize)

Verifies that the mock server received the specified number of HTTP requests matching all the request conditions defined for this mock.

This method is useful for confirming that a series of operations interact with the server as expected within test scenarios, especially when specific interaction counts are significant.

Attention: Use Mock::assert for the common case of asserting exactly one hit.

§Example

Demonstrates creating a mock, sending multiple requests, and verifying the number of received requests matches expectations.

use httpmock::prelude::*;
use reqwest::blocking::get;

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

// Act: Send multiple requests to the configured path
get(&server.url("/hits")).unwrap();
get(&server.url("/hits")).unwrap();

// Assert: Check that the server received exactly two requests that matched the mock
mock.assert_calls(2);
§Panics

This method will panic if the actual number of hits differs from the specified hits, or if there are issues with the mock server’s availability.

Source

pub async fn assert_hits_async(&self, hits: usize)

👎Deprecated since 0.8.0: please use assert_calls_async instead

Asynchronously verifies that the mock server received the specified number of HTTP requests matching all defined request conditions for this mock.

This method supports asynchronous testing environments, enabling non-blocking verification of multiple interactions with the mock server. It’s particularly useful when exact counts of interactions are critical for test assertions.

Attention: For asserting exactly one request asynchronously, use Mock::assert_async for simpler syntax.

§Example

Demonstrates setting up an asynchronous mock, sending multiple requests, and verifying the number of requests received matches expectations.

use httpmock::prelude::*;
use reqwest::get;

let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
    // Arrange: Start a mock server asynchronously and set up a mock
    let server = MockServer::start_async().await;
    let mut mock = server.mock_async(|when, then| {
        when.path("/hits");
        then.status(200);
    }).await;

    // Act: Send multiple asynchronous requests to the configured path
    get(&server.url("/hits")).await.unwrap();
    get(&server.url("/hits")).await.unwrap();

    // Assert: Check that the server received exactly two requests that matched the mock
    mock.assert_hits_async(2).await;
});
§Panics

This method will panic if the actual number of hits differs from the specified hits, or if there are issues with the mock server’s availability.

Source

pub async fn assert_calls_async(&self, hits: usize)

Asynchronously verifies that the mock server received the specified number of HTTP requests matching all defined request conditions for this mock.

This method supports asynchronous testing environments, enabling non-blocking verification of multiple interactions with the mock server. It’s particularly useful when exact counts of interactions are critical for test assertions.

Attention: For asserting exactly one request asynchronously, use Mock::assert_async for simpler syntax.

§Example

Demonstrates setting up an asynchronous mock, sending multiple requests, and verifying the number of requests received matches expectations.

use httpmock::prelude::*;
use reqwest::get;

let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
    // Arrange: Start a mock server asynchronously and set up a mock
    let server = MockServer::start_async().await;
    let mut mock = server.mock_async(|when, then| {
        when.path("/hits");
        then.status(200);
    }).await;

    // Act: Send multiple asynchronous requests to the configured path
    get(&server.url("/hits")).await.unwrap();
    get(&server.url("/hits")).await.unwrap();

    // Assert: Check that the server received exactly two requests that matched the mock
    mock.assert_calls_async(2).await;
});
§Panics

This method will panic if the actual number of hits differs from the specified hits, or if there are issues with the mock server’s availability.

Source

pub fn hits(&self) -> usize

👎Deprecated since 0.8.0: please use calls instead

Returns the number of times the specified mock has been triggered on the mock server.

This method is useful for verifying that a mock has been invoked the expected number of times, allowing for precise control and assertion of interactions within test scenarios.

§Example

Demonstrates setting up a mock, sending a request, and then verifying that the mock was triggered exactly once.

use httpmock::prelude::*;
use reqwest::blocking::get;

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

// Act: Send a request to the mock path
get(&server.url("/hits")).unwrap();

// Assert: Verify the mock was called once
assert_eq!(1, mock.hits());
§Panics

This method will panic if there are issues accessing the mock server or retrieving the hit count.

Source

pub fn calls(&self) -> usize

Returns the number of times the specified mock has been triggered on the mock server.

This method is useful for verifying that a mock has been invoked the expected number of times, allowing for precise control and assertion of interactions within test scenarios.

§Example

Demonstrates setting up a mock, sending a request, and then verifying that the mock was triggered exactly once.

use httpmock::prelude::*;
use reqwest::blocking::get;

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

// Act: Send a request to the mock path
get(&server.url("/hits")).unwrap();

// Assert: Verify the mock was called once
assert_eq!(1, mock.calls());
§Panics

This method will panic if there are issues accessing the mock server or retrieving the hit count.

Source

pub async fn hits_async(&self) -> usize

👎Deprecated since 0.8.0: please use calls_async instead

Asynchronously returns the number of times the specified mock has been triggered on the mock server.

This method is particularly useful in asynchronous test setups where non-blocking verifications are needed to confirm that a mock has been invoked the expected number of times. It ensures test assertions align with asynchronous operations.

§Example

Demonstrates setting up an asynchronous mock, sending a request, and then verifying the number of times the mock was triggered.

use httpmock::prelude::*;
use reqwest::get;

let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
    // Arrange: Start an asynchronous mock server and create a mock
    let server = MockServer::start_async().await;
    let mut mock = server
        .mock_async(|when, then| {
            when.path("/hits");
            then.status(200);
        })
        .await;

    // Act: Send an asynchronous request to the mock path
    get(&server.url("/hits")).await.unwrap();

    // Assert: Verify the mock was called once
    assert_eq!(1, mock.hits_async().await);
});
§Panics

This method will panic if there are issues accessing the mock server or retrieving the hit count asynchronously.

Source

pub async fn calls_async(&self) -> usize

Asynchronously returns the number of times the specified mock has been triggered on the mock server.

This method is particularly useful in asynchronous test setups where non-blocking verifications are needed to confirm that a mock has been invoked the expected number of times. It ensures test assertions align with asynchronous operations.

§Example

Demonstrates setting up an asynchronous mock, sending a request, and then verifying the number of times the mock was triggered.

use httpmock::prelude::*;
use reqwest::get;

let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
    // Arrange: Start an asynchronous mock server and create a mock
    let server = MockServer::start_async().await;
    let mut mock = server
        .mock_async(|when, then| {
            when.path("/hits");
            then.status(200);
        })
        .await;

    // Act: Send an asynchronous request to the mock path
    get(&server.url("/hits")).await.unwrap();

    // Assert: Verify the mock was called once
    assert_eq!(1, mock.calls_async().await);
});
§Panics

This method will panic if there are issues accessing the mock server or retrieving the hit count asynchronously.

Source

pub fn delete(&mut self)

Removes the specified mock from the mock server. This operation is useful for testing scenarios where the mock should no longer intercept requests, effectively simulating an environment where certain endpoints may go offline or change behavior dynamically during testing.

§Example

Demonstrates creating a mock, verifying its behavior with a request, then deleting the mock and verifying that subsequent requests are not intercepted.

use httpmock::prelude::*;
use reqwest::blocking::get;

// Arrange: Start a mock server and set up a mock
let server = MockServer::start();
let mut mock = server.mock(|when, then| {
   when.path("/test");
   then.status(202);
});

// Act: Send a request to the mock and verify its behavior
let response1 = get(&server.url("/test")).unwrap();
assert_eq!(mock.hits(), 1);  // Verify the mock was called once

// Delete the mock from the server
mock.delete();

// Send another request and verify the response now that the mock is deleted
let response2 = get(&server.url("/test")).unwrap();

// Assert: The first response should be 202 as the mock was active, the second should be 404
assert_eq!(response1.status(), 202);
assert_eq!(response2.status(), 404);

This method ensures that the mock is completely removed, and any subsequent requests to the same path will not be intercepted by this mock, typically resulting in a 404 Not Found response unless another active mock matches the request.

Source

pub async fn delete_async(&self)

Asynchronously deletes this mock from the mock server. This method is the asynchronous equivalent of Mock::delete and is suited for use in asynchronous testing environments where non-blocking operations are preferred.

§Example

Demonstrates creating an asynchronous mock, sending a request to verify its behavior, then deleting the mock and verifying that subsequent requests are not intercepted.

use httpmock::prelude::*;
use reqwest::get;

let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
    // Arrange: Start an asynchronous mock server and create a mock
    let server = MockServer::start_async().await;
    let mut mock = server
        .mock_async(|when, then| {
            when.path("/test");
            then.status(202);
        })
        .await;

    // Act: Send a request to the mock path and verify the mock's hit count
    let response1 = get(&server.url("/test")).await.unwrap();
    assert_eq!(mock.hits_async().await, 1);  // Verify the mock was called once

    // Delete the mock asynchronously from the server
    mock.delete_async().await;

    // Send another request and check the response now that the mock is deleted
    let response2 = get(&server.url("/test")).await.unwrap();

    // Assert: The first response should be 202 as the mock was active, the second should be 404
    assert_eq!(response1.status(), 202);
    assert_eq!(response2.status(), 404);
});

This method ensures that the mock is completely removed asynchronously, and any subsequent requests to the same path will not be intercepted by this mock, typically resulting in a 404 Not Found response unless another active mock matches the request.

Source

pub fn server_address(&self) -> &SocketAddr

Returns the network address of the mock server where the associated mock object is stored.

This method provides access to the IP address and port number of the mock server, useful for connecting to it in tests or displaying its address in debugging output.

§Example

Demonstrates how to retrieve and print the address of a mock server after it has been started.

use httpmock::prelude::*;
use std::net::SocketAddr;

// Arrange: Start a mock server
let server = MockServer::start();

// Print the address of the server
let address: &SocketAddr = server.address();
println!("{}", address);
// Output will be something like "127.0.0.1:12345", where 12345 is the port the server is running on.

Trait Implementations§

Source§

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

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. Read more
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. Read more

Auto Trait Implementations§

§

impl<'a> Freeze for Mock<'a>

§

impl<'a> !RefUnwindSafe for Mock<'a>

§

impl<'a> Send for Mock<'a>

§

impl<'a> Sync for Mock<'a>

§

impl<'a> Unpin for Mock<'a>

§

impl<'a> !UnwindSafe for Mock<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,