What is EasyHttpMock?
EasyHttpMock is a HTTP server mocking framework, with EasyHttpMock, you can easily define how your app should react to a client request, mainly by define a set of expectations on top of request method, uri and its payload.
How EasyHttpMock used to work
EasyHttpMock started with a very naive approach, by simply being a wrapper around a basic http server which do some assertions inside on its request handler.
let mut server = HttpServer::new(tls_server_config());
#[allow(unused_must_use)]
let result = server.start(|req| {
if req.method() == "GET" && req.uri().path() == "/posts/1" {
Ok(make_response(StatusCode::OK, b"Hello World!"))
} else {
Ok(make_response(StatusCode::NOT_FOUND, b"Not found"))
}
})
.await;
result.unwrap_or_else(|err| {
panic!("Failed to start mock server: {}", err);
});
After sometime taking advantage of this approach, I realized the time spending on setup handlers for each test I do was taking a lot of my time when writing project integration tests.
How EastHttpMock works today?
With reusability in mind, I started refactoring code to make API easy to undertand and highly composable.
It’s very intuitive API, allows developers to quickly create a mock and how a request should be validated, alongside how a response should be returned to client.
Now, your http server mock can be started like this:
let config = EasyHttpMockConfig::<VetisAdapter>::default();
let mut server = EasyHttpMock::new(config)?;
let mock = Mock::of(
given(method(Method::GET).and(path("/test"))).will_return(
StatusCode::OK
.respond()
.with_body(b"teste"),
),
);
server.register_mock(mock).await?;;
EasyHttpMock design
Diferently from WireMock, EasyHttpMock allows you to use different http server implementations, from HTTP1 to HTTP3, in that case using Vetis as http server.
By taking advantage of adapter API, EasyHttpMock can work on top of many http server implementations, for now, Vetis Smol and Vetis Tokio are available as choices.
A handy set of matchers for mock creation
EasyHttpMock comes with a basic set of matchers, which includes:
- path (partial, exact match)
- method
- body (exact match, partial with json path or xpath)
and many others.
Caramelo, a EasyHttpMock best friend
All matchers provided by EasyHttpMock are written on top of Caramelo matcher api, by understanding matcher api, you can also add your own matchers to make even more easier to write mock servers!
Closing thoughts
With this article, you could go over the history behind EasyHttpMock, his motivations, how it compares to WireMock and were our mock api shines!
I strongly recommend you visit https://github.com/ararog/easyhttpmock to know more about EasyHttpMock and its features!
Enjoy!
Top comments (2)
github.com/ararog/easyhttpmock
Fixed! Thanks for point this out!