mockito

Struct Mock

Source
pub struct Mock { /* private fields */ }
Expand description

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

Implementations§

Source§

impl Mock

Source

pub fn match_query<M: Into<Matcher>>(self, query: M) -> Self

Allows matching against the query part when responding with a mock.

Note that you can also specify the query as part of the path argument in a mock call, in which case an exact match will be performed. Any future calls of Mock#match_query will override the query matcher.

§Example
use mockito::Matcher;

let mut s = mockito::Server::new();

// This will match requests containing the URL-encoded
// query parameter `greeting=good%20day`
s.mock("GET", "/test")
  .match_query(Matcher::UrlEncoded("greeting".into(), "good day".into()))
  .create();

// This will match requests containing the URL-encoded
// query parameters `hello=world` and `greeting=good%20day`
s.mock("GET", "/test")
  .match_query(Matcher::AllOf(vec![
    Matcher::UrlEncoded("hello".into(), "world".into()),
    Matcher::UrlEncoded("greeting".into(), "good day".into())
  ]))
  .create();

// You can achieve similar results with the regex matcher
s.mock("GET", "/test")
  .match_query(Matcher::Regex("hello=world".into()))
  .create();
Source

pub fn match_header<T: IntoHeaderName, M: Into<Matcher>>( self, field: T, value: M, ) -> Self

Allows matching a particular request header when responding with a mock.

When matching a request, the field letter case is ignored.

§Example
let mut s = mockito::Server::new();

s.mock("GET", "/").match_header("content-type", "application/json");

Like most other Mock methods, it allows chanining:

§Example
let mut s = mockito::Server::new();

s.mock("GET", "/")
  .match_header("content-type", "application/json")
  .match_header("authorization", "password");
Source

pub fn match_body<M: Into<Matcher>>(self, body: M) -> Self

Allows matching a particular request body when responding with a mock.

§Example
let mut s = mockito::Server::new();

s.mock("POST", "/").match_body(r#"{"hello": "world"}"#).with_body("json").create();
s.mock("POST", "/").match_body("hello=world").with_body("form").create();

// Requests passing `{"hello": "world"}` inside the body will be responded with "json".
// Requests passing `hello=world` inside the body will be responded with "form".

// Create a temporary file
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use rand;
use rand::Rng;

let random_bytes: Vec<u8> = (0..1024).map(|_| rand::random::<u8>()).collect();

let mut tmp_file = env::temp_dir();
tmp_file.push("test_file.txt");
let mut f_write = File::create(tmp_file.clone()).unwrap();
f_write.write_all(random_bytes.as_slice()).unwrap();
let mut f_read = File::open(tmp_file.clone()).unwrap();


// the following are equivalent ways of defining a mock matching
// a binary payload
s.mock("POST", "/").match_body(tmp_file.as_path()).create();
s.mock("POST", "/").match_body(random_bytes).create();
s.mock("POST", "/").match_body(&mut f_read).create();
Source

pub fn match_request<F>(self, request_matcher: F) -> Self
where F: Fn(&Request) -> bool + Send + Sync + 'static,

Allows matching the entire request based on a closure that takes the Request object as an argument and returns a boolean value.

§Example
use mockito::Matcher;

let mut s = mockito::Server::new();

// This will match requests that have the x-test header set
// and contain the word "hello" inside the body
s.mock("GET", "/")
    .match_request(|request| {
        request.has_header("x-test") &&
            request.utf8_lossy_body().unwrap().contains("hello")
    })
    .create();
Source

pub fn with_status(self, status: usize) -> Self

Sets the status code of the mock response. The default status code is 200.

§Example
let mut s = mockito::Server::new();

s.mock("GET", "/").with_status(201);
Source

pub fn with_header<T: IntoHeaderName>(self, field: T, value: &str) -> Self

Sets a header of the mock response.

§Example
let mut s = mockito::Server::new();

s.mock("GET", "/").with_header("content-type", "application/json");
Source

pub fn with_header_from_request<T: IntoHeaderName>( self, field: T, callback: impl Fn(&Request) -> String + Send + Sync + 'static, ) -> Self

Sets the headers of the mock response dynamically while exposing the request object.

You can use this method to provide custom headers for every incoming request.

The function must be thread-safe. If it’s a closure, it can’t be borrowing its context. Use move closures and Arc to share any data.

§Example
let mut s = mockito::Server::new();

let _m = s.mock("GET", mockito::Matcher::Any).with_header_from_request("x-user", |request| {
    if request.path() == "/bob" {
        "bob".into()
    } else if request.path() == "/alice" {
        "alice".into()
    } else {
        "everyone".into()
    }
});
Source

pub fn with_body<StrOrBytes: AsRef<[u8]>>(self, body: StrOrBytes) -> Self

Sets the body of the mock response. Its Content-Length is handled automatically.

§Example
let mut s = mockito::Server::new();

s.mock("GET", "/").with_body("hello world");
Source

pub fn with_chunked_body( self, callback: impl Fn(&mut dyn Write) -> Result<()> + Send + Sync + 'static, ) -> Self

Sets the body of the mock response dynamically. The response will use chunked transfer encoding.

The callback function will be called only once. You can sleep in between calls to the writer to simulate delays between the chunks. The callback function can also return an error after any number of writes in order to abort the response.

The function must be thread-safe. If it’s a closure, it can’t be borrowing its context. Use move closures and Arc to share any data.

§Example
let mut s = mockito::Server::new();

s.mock("GET", "/").with_chunked_body(|w| w.write_all(b"hello world"));
Source

pub fn with_body_from_fn( self, callback: impl Fn(&mut dyn Write) -> Result<()> + Send + Sync + 'static, ) -> Self

👎Deprecated since 1.0.0: Use Mock::with_chunked_body instead

DEPRECATED: Replaced by Mock::with_chunked_body.

Source

pub fn with_body_from_request( self, callback: impl Fn(&Request) -> Vec<u8> + Send + Sync + 'static, ) -> Self

Sets the body of the mock response dynamically while exposing the request object.

You can use this method to provide a custom reponse body for every incoming request.

The function must be thread-safe. If it’s a closure, it can’t be borrowing its context. Use move closures and Arc to share any data.

§Example
let mut s = mockito::Server::new();

let _m = s.mock("GET", mockito::Matcher::Any).with_body_from_request(|request| {
    if request.path() == "/bob" {
        "hello bob".into()
    } else if request.path() == "/alice" {
        "hello alice".into()
    } else {
        "hello world".into()
    }
});
Source

pub fn with_body_from_file(self, path: impl AsRef<Path>) -> Self

Sets the body of the mock response from the contents of a file stored under path. Its Content-Length is handled automatically.

§Example
let mut s = mockito::Server::new();

s.mock("GET", "/").with_body_from_file("tests/files/simple.http");
Source

pub fn expect(self, hits: usize) -> Self

Sets the expected amount of requests that this mock is supposed to receive. This is only enforced when calling the assert method. Defaults to 1 request.

Source

pub fn expect_at_least(self, hits: usize) -> Self

Sets the minimum amount of requests that this mock is supposed to receive. This is only enforced when calling the assert method.

Source

pub fn expect_at_most(self, hits: usize) -> Self

Sets the maximum amount of requests that this mock is supposed to receive. This is only enforced when calling the assert method.

Source

pub fn assert(&self)

Asserts that the expected amount of requests (defaults to 1 request) were performed.

Source

pub async fn assert_async(&self)

Same as Mock::assert but async.

Source

pub fn matched(&self) -> bool

Returns whether the expected amount of requests (defaults to 1) were performed.

Source

pub async fn matched_async(&self) -> bool

Same as Mock::matched but async.

Source

pub fn create(self) -> Mock

Registers the mock to the server - your mock will be served only after calling this method.

§Example
let mut s = mockito::Server::new();

s.mock("GET", "/").with_body("hello world").create();
Source

pub async fn create_async(self) -> Mock

Same as Mock::create but async.

Source

pub fn remove(&self)

Removes the mock from the server.

Source

pub async fn remove_async(&self)

Same as Mock::remove but async.

Trait Implementations§

Source§

impl Debug for Mock

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Mock

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for Mock

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl PartialEq for Mock

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

§

impl !Freeze for Mock

§

impl !RefUnwindSafe for Mock

§

impl Send for Mock

§

impl Sync for Mock

§

impl Unpin for Mock

§

impl !UnwindSafe for Mock

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

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

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

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

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more