Struct wiremock::Mock[][src]

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, 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, 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, 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, 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, 404);
}

pub fn expect<T: Into<Times>>(self, r: T) -> Self[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 and the error_message is shown.

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..)
        // We assign a name to the mock - it will be shown in error messages
        // if our expectation is not verified!
        .named("Root GET")
        .mount(&mock_server)
        .await;
     
    // Act
    let status = surf::get(&mock_server.uri())
        .await
        .unwrap()
        .status();
    assert_eq!(status, 200);

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

pub fn named<T: Into<String>>(self, mock_name: T) -> Self[src]

Assign a name to your mock.

The mock name will be used in error messages (e.g. if the mock expectation is not satisfied) and debug logs to help you identify what failed.

Example:

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

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

    // We have two mocks in the same test - how do we find out
    // which one failed when the test panics?
    // Assigning a name to each mock with `named` gives us better error
    // messages and makes it much easier to debug why a test is failing!
    Mock::given(method("GET"))
        .respond_with(ResponseTemplate::new(200))
        .up_to_n_times(2)
        .expect(1..)
        // We assign a name to the mock - it will be shown in error messages
        // if our expectation is not verified!
        .named("Root GET")
        .mount(&mock_server)
        .await;

    Mock::given(method("POST"))
        .respond_with(ResponseTemplate::new(200))
        .up_to_n_times(2)
        .expect(1..)
        // We assign a name to the mock - it will be shown in error messages
        // if our expectation is not verified!
        .named("Root POST")
        .mount(&mock_server)
        .await;
     
    // Act
    let status = surf::get(&mock_server.uri())
        .await
        .unwrap()
        .status();
    assert_eq!(status, 200);

    // Assert
    // We did not make a POST request, therefore the expectation on `Root POST`
    // is not satisfied and the test will panic.
}

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!

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> 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> Instrument for T[src]

impl<T> Instrument for T[src]

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

impl<T> Same<T> for T

type Output = T

Should always be Self

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>, 

impl<T> WithSubscriber for T[src]