[][src]Struct httpmock::Mock

pub struct Mock { /* fields omitted */ }

Represents the primary interface to the mock server.

Example

extern crate httpmock;

use httpmock::{mock, with_mock_server};
use httpmock::Method::GET;

#[test]
#[with_mock_server]
fn simple_test() {
   let search_mock = mock(GET, "/health")
      .return_status(200)
      .create();

   // Act (simulates your code)
   let response = reqwest::get("http://localhost:5000/health").unwrap();

   // Make some assertions
   assert_eq!(response.status(), 200);
   assert_eq!(search_mock.times_called().unwrap(), 1);
}

To be able to create a mock, you need to mark your test function with the httpmock::with_mock_server attribute. If you try to create a mock by calling Mock::create without marking your test function with httpmock::with_mock_server, you will receive a panic during runtime telling you about this fact.

Note that you need to call the Mock::create method once you are finished configuring your mock. This will create the mock on the server. Thereafter, the mock will be served whenever clients send HTTP requests that match all requirements of your mock.

The Mock::create method returns a reference that identifies the mock at 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.

While httpmock::mock is a convenience function, you can have more control over matching the path by directly creating a new Mock object yourself using the Mock::new method.

Example

extern crate httpmock;

use httpmock::Method::POST;
use httpmock::{Mock, Regex, with_mock_server};

#[test]
#[with_mock_server]
fn simple_test() {
    Mock::new()
      .expect_path("/test")
      .expect_path_contains("test")
      .expect_path_matches(Regex::new(r#"test"#).unwrap())
      .expect_method(POST)
      .return_status(200)
      .create();
}

Fore more examples, please refer to this crates test directory.

Methods

impl Mock[src]

pub fn new() -> Mock[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).

Important Notice

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:

use httpmock::Method::POST;
use httpmock::mock;

#[test]
#[with_mock_server]
fn partial_json_test() {
    mock(POST, "/path")
        .expect_json_body_partial(r#"
            {
                "child" : {
                    "target_attribute" : "Target value"
                }
            }
        "#)
        .return_status(200)
        .create();
}

String format and attribute order will be ignored.

  • partial - The JSON partial.

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 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 create(self) -> Self[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 your test method was not marked using the the httpmock::with_mock_server annotation.

pub fn times_called(&self) -> usize[src]

This method returns the number of times a mock has been called at the mock server.

Panics

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

pub fn server_port(&self) -> u16[src]

Returns the port of the mock server this mock is using. By default this is port 5000 if not set otherwise by the environment variable HTTPMOCK_PORT.

pub fn server_host(&self) -> &str[src]

Returns the host of the mock server this mock is using. By default this is localhost if not set otherwise by the environment variable HTTPMOCK_HOST.

pub fn server_address(&self) -> String[src]

Returns the address of the mock server this mock is using. By default this is "localhost:5000" if not set otherwise by the environment variables HTTPMOCK_HOST and HTTPMOCK_PORT.

pub fn delete(&mut self)[src]

Deletes this mock from the mock server.

Panics

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

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