Crate mockito [] [src]

Mockito is a library for creating HTTP mocks to be used in integration tests or for offline work. It runs an HTTP server on your local port 1234 and can register and remove mocks.

The server is run on a separate thread within the same process and will be cleaned up at the end of the run.

Getting Started

Using compiler flags, set the URL of your web client to mockito::SERVER_URL or mockito::SERVER_ADDRESS.

Example

#[cfg(test)]
use mockito;

#[cfg(not(test))]
const URL: &'static str = "https://api.twitter.com";

#[cfg(test)]
const URL: &'static str = mockito::SERVER_URL;

Then start mocking:

Example

#[cfg(test)]
mod tests {
  use mockito::mock;

  #[test]
  fn test_something() {
    mock("GET", "/hello")
      .with_status(201)
      .with_header("content-type", "text/plain")
      .with_header("x-api-key", "1234")
      .with_body("world")
      .create();

    // Any calls to GET /hello beyond this line will respond with 201, the
    // `content-type: text/plain` header and the body "world".
  }
}

Run your tests

Due to the nature of this library (all your mocks are recorded on the same server running in background), it is highly recommended that you run your tests on a single thread:

cargo test -- --test-threads=1

# Same, but using an environment variable
RUST_TEST_THREADS=1 cargo test

In some situations, when you're always testing/mocking different routes and never need to reset or override the existing mocks, you might get away with running your tests on multiple threads.

Asserts

You can use the Mock::assert method to assert that a mock was called. By default, the method expects that only one request to your mock was triggered.

Example

extern crate mockito;
extern crate curl;

let mut mock = mockito::mock("GET", "/hello");
mock.create();

let mut request = curl::easy::Easy::new();
request.url(&[mockito::SERVER_URL, "/hello"].join("")).unwrap();
request.perform().unwrap();

mock.assert();

However, you can use the Mock::expect method to specify the exact amount of requests you are expecting:

Example

extern crate mockito;
extern crate curl;

let mut mock = mockito::mock("GET", "/hello");
mock.expect(3).create();

for _ in 0..3 {
    let mut request = curl::easy::Easy::new();
    request.url(&[mockito::SERVER_URL, "/hello"].join("")).unwrap();
    request.perform().unwrap();
}

mock.assert();

Matchers

Mockito can match your request by method, path and headers.

Various matchers are provided by the Matcher type: exact, partial (regular expressions), any or missing.

Matching by path

By default, the request path is compared by its exact value:

Example

use mockito::mock;

// Matched only calls to GET /hello
mock("GET", "/hello").create();

You can also match the path partially, by using a regular expression:

Example

use mockito::{mock, Matcher};

// Will match calls to GET /hello/1 and GET /hello/2
mock("GET", Matcher::Regex(r"^/hello/(1|2)$".to_string())).create();

Or you can catch all requests, by using the Matcher::Any variant:

Example

use mockito::{mock, Matcher};

// Will match any GET request
mock("GET", Matcher::Any).create();

Matching by header

By default, headers are compared by their exact value. The header name letter case is ignored though.

Example

use mockito::mock;

mock("GET", "/hello")
  .match_header("content-type", "application/json")
  .with_body("{'hello': 'world'}")
  .create();

mock("GET", "/hello")
  .match_header("content-type", "text/plain")
  .with_body("world")
  .create();

// JSON requests to GET /hello will respond with JSON, while plain requests
// will respond with text.

You can also match a header value with a regular expressions, by using the Matcher::Regex matcher:

Example

use mockito::{mock, Matcher};

mock("GET", "/hello")
  .match_header("content-type", Matcher::Regex(r".*json.*".to_string()))
  .with_body("{'hello': 'world'}")
  .create();

Or you can match a header only by its field name, by setting the Mock::match_header value to Matcher::Any.

Example

use mockito::{mock, Matcher};

mock("GET", "/hello")
 .match_header("content-type", Matcher::Any)
 .with_body("something");

// Requests containing any content-type header value will be mocked.
// Requests not containing this header will return `501 Not Implemented`.

You can mock requests that should be missing a particular header field, by setting the Mock::match_header value to Matcher::Missing.

Example

use mockito::{mock, Matcher};

mock("GET", "/hello")
  .match_header("authorization", Matcher::Missing)
  .with_body("no authorization header");

// Requests without the authorization header will be matched.
// Requests containing the authorization header will return `501 Not Implemented`.

Non-matching calls

Any calls to the Mockito server that are not matched will return 501 Not Implemented.

Cleaning up

Even though mocks are matched in reverse order (most recent one wins), in some situations it might be useful to clean up right after the test. There are multiple ways of doing this.

By using a closure:

Example

use mockito::mock;

mock("GET", "/hello")
  .with_body("world")
  .create_for(|| {
    // mock only valid for the lifetime of this closure
    // NOTE: it might still be accessible by separate threads
  });

By calling remove() on the mock:

Example

use mockito::mock;

let mut mock = mock("GET", "/hello");
mock.with_body("world").create();

// do your thing

mock.remove();

By calling reset() to remove all mocks:

Example

use mockito::reset;

reset();

Structs

Mock

Stores information about a mocked request. Should be initialized via mockito::mock().

Enums

Matcher

Allows matching the request path or headers in multiple ways: matching the exact value, matching any value (as long as it is present), matching by regular expression or checking that a particular header is missing.

Constants

SERVER_ADDRESS

Points to the address the mock server is running at. Can be used with std::net::TcpStream.

SERVER_URL

Points to the URL the mock server is running at.

Functions

mock

Initializes a mock for the provided method and path.

reset

Removes all the mocks stored on the server.

start