[][src]Struct wiremock::Mock

pub struct Mock { /* fields omitted */ }

Given a set of matchers, a Mock instructs an instance of MockServer to return a pre-determined response if the matching conditions are satisfied.

Mocks have to be mounted (or registered) with a MockServer to become effective.

Example (using register):

use wiremock::{MockServer, Mock, ResponseTemplate};
use wiremock::matchers::method;

#[async_std::main]
async fn main() {
    // Arrange
    let mock_server = MockServer::start().await;

    let response = ResponseTemplate::new(200);

    let mock = Mock::given(method("GET")).respond_with(response.clone());
    // Registering the mock with the mock server - it's now effective!
    mock_server.register(mock).await;

    // We won't register this mock instead.
    let unregistered_mock = Mock::given(method("GET")).respond_with(response);
     
    // Act
    let status = surf::get(&mock_server.uri())
        .await
        .unwrap()
        .status();
    assert_eq!(status.as_u16(), 200);

    // This would have matched `unregistered_mock`, but we haven't registered it!
    // Hence it returns a 404, the default response when no mocks matched on the mock server.
    let status = surf::post(&mock_server.uri())
        .await
        .unwrap()
        .status();
    assert_eq!(status.as_u16(), 404);
}

Example (using mount):

If you prefer a fluent style, you can use the mount method on the Mock itself instead of register.

use wiremock::{MockServer, Mock, ResponseTemplate};
use wiremock::matchers::method;

#[async_std::main]
async fn main() {
    // Arrange
    let mock_server = MockServer::start().await;

    Mock::given(method("GET"))
        .respond_with(ResponseTemplate::new(200))
        .up_to_n_times(1)
        // Mounting the mock on the mock server - it's now effective!
        .mount(&mock_server)
        .await;
     
    // Act
    let status = surf::get(&mock_server.uri())
        .await
        .unwrap()
        .status();
    assert_eq!(status.as_u16(), 200);
}

Both register and mount are asynchronous methods - don't forget to .await them!

Implementations

impl Mock[src]

pub fn given<M: 'static + Match>(matcher: M) -> MockBuilder[src]

Start building a Mock specifying the first matcher.

It returns an instance of MockBuilder.

pub fn up_to_n_times(self, n: u64) -> Mock[src]

Specify an upper limit to the number of times you would like this Mock to respond to incoming requests that satisfy the conditions imposed by your matchers.

Example:

use wiremock::{MockServer, Mock, ResponseTemplate};
use wiremock::matchers::method;

#[async_std::main]
async fn main() {
    // Arrange
    let mock_server = MockServer::start().await;

    Mock::given(method("GET"))
        .respond_with(ResponseTemplate::new(200))
        // Default behaviour will have this Mock responding to any incoming request
        // that satisfied our matcher (e.g. being a GET request).
        // We can opt out of the default behaviour by setting a cap on the number of
        // matching requests this Mock should respond to.
        //
        // In this case, once one matching request has been received, the mock will stop
        // matching additional requests and you will receive a 404 if no other mock
        // matches on those requests.
        .up_to_n_times(1)
        .mount(&mock_server)
        .await;
     
    // Act

    // The first request matches, as expected.
    let status = surf::get(&mock_server.uri())
        .await
        .unwrap()
        .status();
    assert_eq!(status.as_u16(), 200);

    // The second request does NOT match given our `up_to_n_times(1)` setting.
    let status = surf::get(&mock_server.uri())
        .await
        .unwrap()
        .status();
    assert_eq!(status.as_u16(), 404);
}

pub fn expect<T: Into<Times>>(self, r: T) -> Mock[src]

Set an expectation on the number of times this Mock should match in the current test case. Expectations are verified when the MockServer is shutting down: if the expectation is not satisfied, the MockServer will panic.

By default, no expectation is set for Mocks.

When is this useful?

expect can turn out handy when you'd like to verify that a certain side-effect has (or has not!) taken place.

For example:

  • check that a 3rd party notification API (e.g. email service) is called when an event in your application is supposed to trigger a notification;
  • check that a 3rd party API is NOT called when the response of a call is expected to be retrieved from a cache (.expect(0)).

This technique is also called spying.

Example:

use wiremock::{MockServer, Mock, ResponseTemplate};
use wiremock::matchers::method;

#[async_std::main]
async fn main() {
    // Arrange
    let mock_server = MockServer::start().await;

    Mock::given(method("GET"))
        .respond_with(ResponseTemplate::new(200))
        .up_to_n_times(2)
        // We expect the mock to be called at least once.
        // If that does not happen, the `MockServer` will panic on shutdown,
        // causing the whole test to fail.
        .expect(1..)
        .mount(&mock_server)
        .await;
     
    // Act
    let status = surf::get(&mock_server.uri())
        .await
        .unwrap()
        .status();
    assert_eq!(status.as_u16(), 200);

    // Assert
    // We made at least one matching request, the expectation is satisfied.
    // The `MockServer` will shutdown peacefully, without panicking.
}

pub async fn mount<'_>(self, server: &'_ MockServer)[src]

Mount a Mock on an instance of MockServer.

Be careful! Mocks are not effective until they are mounted or registered on a MockServer.

mount is an asynchronous method, make sure to .await it!

pub fn response(&self) -> Response[src]

Build an instance of http_types::Response from the ResponseTemplate associated with a Mock.

Trait Implementations

impl Debug for Mock[src]

Auto Trait Implementations

impl !RefUnwindSafe for Mock

impl Send for Mock

impl Sync for Mock

impl Unpin for Mock

impl !UnwindSafe for Mock

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> AsAny for T where
    T: Any

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> Message for T where
    T: Any + Send + Sync + Debug
[src]

impl<T> Same<T> for T

type Output = T

Should always be Self

impl<T> State for T where
    T: Send + Sync + 'static, 

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.

impl<V, T> VZip<V> for T where
    V: MultiLane<T>,