Mocking HTTP calls for Unit tests in Rust

Money Grows on Trees
1 min readAug 27, 2020
Photo by freestocks on Unsplash

Motivation: HTTP calls should be mocked, we don’t want to make HTTP calls every time we run our tests and it also makes them faster to run!

The tutorial will be referring to httpmock v0.4.2 mocking library (There are other mocking libraries like mockito

Where to begin?

Let’s start with how you can import httpmock

[dev-dependencies]
httpmock = "0.4.2"

Now, let’s mock something with this amazing library

// you could import any of the HTTP methods you are using
use httpmock::Method::GET;
use httpmock::{Mock, MockServer};
...
fn test_with_mock_server() {

let mock_server = MockServer::start();

// you can also connect to a remote server using connect()
let server = MockServer::connect("server_address");
// create a mock on mock_server
let mock = Mock::new()
.expect_method(GET)
.expect_path("/hello")
.return_status(200)
.create_on(&mock_server);
// we can find out number of times mock is invoked
assert_eq!(hello_mock.times_called(), 1);
// mocks can also be deleted
hello_mock.delete();
}

And that is it, you can now mock HTTP requests in Rust

If you need to inject your mock_server’s URL into a struct, you can use mock_server.url(“”) to fetch the mock_server’s address in case you used the MockServer::start() method.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response