27 releases

0.5.8 Apr 18, 2021
0.5.7 Mar 22, 2021
0.5.5 Jan 28, 2021
0.5.2 Oct 25, 2020
0.3.3 Oct 3, 2019

#11 in Testing

Download history 1803/week @ 2021-01-14 1046/week @ 2021-01-21 1841/week @ 2021-01-28 1432/week @ 2021-02-04 3162/week @ 2021-02-11 2967/week @ 2021-02-18 3324/week @ 2021-02-25 3594/week @ 2021-03-04 3450/week @ 2021-03-11 3327/week @ 2021-03-18 3085/week @ 2021-03-25 4046/week @ 2021-04-01 4080/week @ 2021-04-08 4214/week @ 2021-04-15 4940/week @ 2021-04-22 4839/week @ 2021-04-29

12,556 downloads per month
Used in less than 13 crates

MIT license

270KB
4.5K SLoC

httpmock

HTTP mocking library for Rust.

Build Status codecov crates.io Rust License

Documentation · Crate · Report Bug · Request Feature · Changelog

Features

  • Simple, expressive, fluent API.
  • Many built-in helpers for easy request matching.
  • Parallel test execution.
  • Extensible request matching.
  • Fully asynchronous core with synchronous and asynchronous APIs.
  • Debugging support.
  • Network delay simulation.
  • Support for Regex matching, JSON, serde, cookies, and more.
  • Standalone mode with an accompanying Docker image.
  • Support for mock specification based on YAML files.

Getting Started

Add httpmock to Cargo.toml:

[dev-dependencies]
httpmock = "0.5"

You can then use httpmock as follows:

use httpmock::MockServer;
use httpmock::Method::GET;

// Start a lightweight mock server.
let server = MockServer::start();

// Create a mock on the server.
let hello_mock = server.mock(|when, then| {
    when.method(GET)
        .path("/translate")
        .query_param("word", "hello");
    then.status(200)
        .header("Content-Type", "text/html; charset=UTF-8")
        .body("Привет");
});

// Send an HTTP request to the mock server. This simulates your code.
let response = isahc::get(server.url("/translate?word=hello")).unwrap();

// Ensure the specified mock was called exactly one time (or fail with a detailed error description).
hello_mock.assert();
// Ensure the mock server did respond as specified.
assert_eq!(response.status(), 200);

The above example will spin up a lightweight HTTP mock server and configure it to respond to all GET requests to path /translate with query parameter word=hello. The corresponding HTTP response will contain the text body Привет.

Usage

See the reference docs for detailed API documentation.

Examples

You can find examples in the httpmock test directory. The reference docs also contain a lot of examples. There is an online tutorial as well.

License

httpmock is free software: you can redistribute it and/or modify it under the terms of the MIT Public License.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MIT Public License for more details.

Dependencies

~24MB
~517K SLoC