yjlee
yjlee

Reputation: 545

When using httpmock in Rust, can one mock server handle multiple paths?

I'm testing the engine's register and poll(health check at regular intervals) behavior by making a mock server that replaces the admin server.

let admin_mock_server = admin_server.mock(|when, then| {
        when.path("/register")
            .header("content-type", "application/json")
            .header_exists("content-type")
            .json_body_partial(
                r#"
                    {
                        "engineName": "engine_for_mock"
                    }
                    "#,
            );
        then.status(200)
            .header("content-type", "application/json")
            .json_body(get_sample_register_response_body());
    });

After performing the register operation, a poll message is sent to the same admin server. Therefore, to test this behavior, I must send a poll message to the same mock server.

Is there a way to set up two pairs of request-response(when-then) on one mock server?

        when.path("/poll");
        then.status(200)
            .header("content-type", "application/json")
            .json_body(get_sample_poll_response_body());
    

Upvotes: 2

Views: 810

Answers (1)

gnapoli23
gnapoli23

Reputation: 46

If you look a the doc here: https://docs.rs/httpmock/latest/httpmock/struct.MockServer.html

you can see that the mockfunction returns a Mock object on the mock server. By this, i guess you can add more mocks on the same server by simply doing the same operations you did for the registerendpoint.

let mock_register = admin_server.mock(|when, then| {
   ...
});

let mock_poll = admin_server.mock(|when, then| {
   ...
});

In this way you would have two different mocks on the same admin_server, and then you can put in you test

mock_register.assert()
...

mock_poll.assert()

to interact with those two different endpoints.

Upvotes: 3

Related Questions