HTTP mocking for Rust!
colored
crateSemaphore::const_new
wasn't available on Tokio < 1.30 because of the missing Tokio parking_lot
feature flagfutures
crate (aside from futures-core
)Thanks to @tottoto
Server::new_with_opts
, Server::new_with_opts_async
and the ServerOpts
struct to allow configuring the server host, port and enabling auto-asserts (see next item)assert_on_drop
server option that allows you to automatically call assert()
whenever your mocks go out of scope (defaults to false)Server::socket_address()
to return the raw server SocketAddr
hyper::header::HeaderValue
as a match_header()
valueThanks to @andrewtoth @alexander-jackson
mac_os
targets to prevent hitting the file descriptor limitThanks to @kornelski
with_chunked_body
supports streaming responses (as opposed to writing the entire buffer in one go)Thanks to @kornelski
futures::future::join_all
would block the server pool.Server::reset_async
has been deprecated in favour of Server::reset
since the former doesn't have an async implementation any more.:balloon: 7 years and 63 releases later, it's finally time for the 1.0 :balloon:
Mock::with_body_from_fn
was renamed to Mock::with_chunked_body
- the former is still supported with a deprecation warningMock::remove
and Mock::remove_async
methods to remove mocks on demandFor a list of all the changes please check the release log.
Legacy API:
let m1 = mockito::mock("GET", "/hello").with_body("hello").create();
let m2 = mockito::mock("GET", "/bye").with_body("bye").create();
// Use one of these to configure your client
let host = mockito:server_address();
let url = mockito::server_url();
New API:
let mut server = mockito::Server::new();
server.mock("GET", "/hello").with_body("hello").create();
server.mock("GET", "/bye").with_body("bye").create();
// Use one of these to configure your client
let host = server.host_with_port();
let url = server.url();
If you can't migrate to the new API in one go, consider using version 0.32.5, which supports both the legacy API as well as the new API.
In order to write async tests, you'll need to use the _async
methods:
Server::new_async
Mock::create_async
Mock::assert_async
Mock::matched_async
Mock::remove_async
Server::reset_async
...otherwise your tests will not compile and you'll see this error:
Cannot block the current thread from within a runtime. This happens because a function attempted
to block the current thread while the thread is being used to drive asynchronous tasks.
Example:
#[tokio::test]
async fn test_simple_route_mock_async() {
let mut server = Server::new_async().await;
let m1 = server.mock("GET", "/a").with_body("aaa").create_async().await;
let m2 = server.mock("GET", "/b").with_body("bbb").create_async().await;
let (m1, m2) = futures::join!(m1, m2);
// You can use `Mock::assert_async` to verify that your mock was called
// m1.assert_async().await;
// m2.assert_async().await;
}
Arc
(more reliable in this case)