[][src]Struct httpmock::Mock

pub struct Mock { /* fields omitted */ }

Represents the primary interface to the mock server.

Example

extern crate httpmock;

use httpmock::Method::{GET};
use httpmock::{Mock, MockServer};

#[test]
fn example_test() {
    // Arrange
    let mock_server = MockServer::start();
    let search_mock = Mock::new()
        .expect_path_contains("/search")
        .expect_query_param("query", "metallica")
        .return_status(202)
        .create_on(&mock_server);

    // Act: Send the HTTP request
    let response = isahc::get(&format!(
        "http://{}/search?query=metallica",
        mock_server.address()
    )).unwrap();

    // Assert
    assert_eq!(response.status(), 202);
    assert_eq!(search_mock.times_called(), 1);
}

Make sure to create the mock using Mock::create_on or Mock::create_on_async. This will create the mock on the server. Thereafter, the mock will be served whenever clients send HTTP requests that match all mock requirements.

The Mock::create_on and Mock::create_on_async methods return a mock reference object that identifies the mock on the server side. The reference can be used to fetch mock related information from the server, such as the number of times it has been called or to explicitly delete the mock from the server (see MockRef::delete). Fore more examples, please refer to this crates test directory.

Implementations

impl Mock[src]

pub fn new() -> Self[src]

Creates a new mock that automatically returns HTTP status code 200 if hit by an HTTP call.

pub fn expect_path(self, path: &str) -> Self[src]

Sets the expected path. If the path of an HTTP request at the server is equal to the provided path, the request will be considered a match for this mock to respond (given all other criteria are met).

  • path - The exact path to match against.

pub fn expect_path_contains(self, substring: &str) -> Self[src]

Sets an expected path substring. If the path of an HTTP request at the server contains t, his substring the request will be considered a match for this mock to respond (given all other criteria are met).

  • substring - The substring to match against.

pub fn expect_path_matches(self, regex: Regex) -> Self[src]

Sets an expected path regex. If the path of an HTTP request at the server matches this, regex the request will be considered a match for this mock to respond (given all other criteria are met).

  • regex - The regex to match against.

pub fn expect_method(self, method: Method) -> Self[src]

Sets the expected HTTP method. If the path of an HTTP request at the server matches this regex, the request will be considered a match for this mock to respond (given all other criteria are met).

  • method - The HTTP method to match against.

pub fn expect_header(self, name: &str, value: &str) -> Self[src]

Sets an expected HTTP header. If one of the headers of an HTTP request at the server matches the provided header key and value, the request will be considered a match for this mock to respond (given all other criteria are met).

  • name - The HTTP header name (header names are case-insensitive by RFC 2616).
  • value - The HTTP header value.

pub fn expect_header_exists(self, name: &str) -> Self[src]

Sets an expected HTTP header to exists. If one of the headers of an HTTP request at the server matches the provided header name, the request will be considered a match for this mock to respond (given all other criteria are met).

  • name - The HTTP header name (header names are case-insensitive by RFC 2616).

pub fn expect_body(self, contents: &str) -> Self[src]

Sets the expected HTTP body. If the body of an HTTP request at the server matches the provided body, the request will be considered a match for this mock to respond (given all other criteria are met). This is an exact match, so all characters are taken into account, such as whitespace, tabs, etc.

  • contents - The HTTP body to match against.

pub fn expect_json_body<T>(self, body: &T) -> Self where
    T: Serialize
[src]

Sets the expected HTTP body JSON string. This method expects a serializable serde object that will be parsed into JSON. If the body of an HTTP request at the server matches the body according to the provided JSON object, the request will be considered a match for this mock to respond (given all other criteria are met).

This is an exact match, so all characters are taken into account at the server side.

The provided JSON object needs to be both, a deserializable and serializable serde object. Note that this method does not set the "Content-Type" header automatically, so you need to provide one yourself!

  • body - The HTTP body object that will be serialized to JSON using serde.

pub fn expect_json_body_partial(self, partial: &str) -> Self[src]

Sets an expected partial HTTP body JSON string.

If the body of an HTTP request at the server matches the partial, the request will be considered a match for this mock to respond (given all other criteria are met).

  • partial - The JSON partial.

Important

The partial string needs to contain the full JSON object path from the root.

Example

If your application sends the following JSON request data to the mock server

{
    "parent_attribute" : "Some parent data goes here",
    "child" : {
        "target_attribute" : "Target value",
        "other_attribute" : "Another value"
    }
}

and you only want to make sure that target_attribute has the value Target value, you need to provide a partial JSON string to this method, that starts from the root of the JSON object, but may leave out unimportant values:

extern crate httpmock;

use httpmock::Method::{GET};
use httpmock::{Mock, MockServer};

#[test]
fn delete_mock_test() {
    // Arrange: Create mock server and a mock
    let mock_server = MockServer::start();
    let mut mock = Mock::new()
        .expect_json_body_partial(r#"
            {
                "child" : {
                    "target_attribute" : "Target value"
                }
            }
        "#)
        .return_status(202)
        .create_on(&mock_server);

    // ...
}

String format and attribute order will be ignored.

pub fn expect_body_contains(self, substring: &str) -> Self[src]

Sets an expected HTTP body substring. If the body of an HTTP request at the server contains the provided substring, the request will be considered a match for this mock to respond (given all other criteria are met).

  • substring - The substring that will matched against.

pub fn expect_body_matches(self, regex: Regex) -> Self[src]

Sets an expected HTTP body regex. If the body of an HTTP request at the server matches the provided regex, the request will be considered a match for this mock to respond (given all other criteria are met).

  • regex - The regex that will matched against.

pub fn expect_query_param(self, name: &str, value: &str) -> Self[src]

Sets an expected query parameter. If the query parameters of an HTTP request at the server contains the provided query parameter name and value, the request will be considered a match for this mock to respond (given all other criteria are met).

  • name - The query parameter name that will matched against.
  • value - The value parameter name that will matched against.

pub fn expect_query_param_exists(self, name: &str) -> Self[src]

Sets an expected query parameter name. If the query parameters of an HTTP request at the server contains the provided query parameter name (not considering the value), the request will be considered a match for this mock to respond (given all other criteria are met).

  • name - The query parameter name that will matched against.

pub fn expect_match(
    self,
    request_matcher: fn(_: Rc<MockServerHttpRequest>) -> bool
) -> Self
[src]

Sets a custom matcher for expected HTTP request. If this function returns true, the request is considered a match and the mock server will respond to the request (given all other criteria are also met).

  • request_matcher - The matcher function.

Example:

use httpmock::{MockServerRequest, MockServer, Mock};

#[test]
fn custom_matcher_test() {
    // Arrange
    let mock_server = MockServer::start();
    let m = Mock::new()
        .expect_match(|req: MockServerRequest| {
            req.path.contains("es")
        })
        .return_status(200)
        .create_on(&mock_server);

    // Act: Send the HTTP request
    let response = isahc::get(mock_server.url("/test")).unwrap();

    // Assert
    assert_eq!(response.status(), 200);
    assert_eq!(m.times_called(), 1);
}

pub fn return_status(self, status: usize) -> Self[src]

Sets the HTTP status that the mock will return, if an HTTP request fulfills all of the mocks requirements.

  • status - The HTTP status that the mock server will return.

pub fn return_body(self, body: &str) -> Self[src]

Sets the HTTP response body that the mock will return, if an HTTP request fulfills all of the mocks requirements.

  • body - The HTTP response body that the mock server will return.

pub fn return_json_body<T>(self, body: &T) -> Self where
    T: Serialize
[src]

Sets the HTTP response JSON body that the mock will return, if an HTTP request fulfills all of the mocks requirements.

The provided JSON object needs to be both, a deserializable and serializable serde object. Note that this method does not set the "Content-Type" header automatically, so you need to provide one yourself!

  • body - The HTTP response body the mock server will return in the form of a JSON string.

pub fn return_header(self, name: &str, value: &str) -> Self[src]

Sets an HTTP header that the mock will return, if an HTTP request fulfills all of the mocks requirements.

  • name - The name of the header.
  • value - The value of the header.

pub fn return_with_delay(self, duration: Duration) -> Self[src]

Sets a duration that will delay the mock server response.

  • duration - The delay.

pub fn create_on<'a>(self, mock_server: &'a MockServer) -> MockRef<'a>[src]

This method creates the mock at the server side and returns a Mock object representing the reference of the created mock at the server.

Panics

This method will panic if there is a problem communicating with the server.

pub async fn create_on_async<'a>(
    self,
    mock_server: &'a MockServer
) -> MockRef<'a>
[src]

This method creates the mock at the server side and returns a Mock object representing the reference of the created mock at the server. This method is the asynchronous counterpart of Mock::create_on.

Panics

This method will panic if there is a problem communicating with the server.

Trait Implementations

impl Default 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> 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, U> Into<U> for T where
    U: From<T>, 
[src]

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