Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to override mock behaviour #150

Open
mawkler opened this issue Oct 26, 2024 · 2 comments
Open

Unable to override mock behaviour #150

mawkler opened this issue Oct 26, 2024 · 2 comments

Comments

@mawkler
Copy link

mawkler commented Oct 26, 2024

I'm trying to mock an overcomplicated API that I don't own, but that my code makes calls to. For each of my tests I have to mock quite a lot of endpoints, but most of them should behave the same way for all tests. I would therefore like to create a "base mock" that mocks all those endpoints, and then I want to override the base behaviour of one of those endpoints depending on the test.

However, it seems like I can't override the response for a given path if I've already defined it. Here's some code to illustrate the behaviour that I expect:

use wiremock::{Mock, MockServer, ResponseTemplate};
use wiremock::matchers::{method, path};
use reqwest;

#[tokio::main]
async fn main() {
    let mock_server = MockServer::start().await;

    // Define base behavior
    Mock::given(method("GET"))
        .and(path("/api/base"))
        .respond_with(ResponseTemplate::new(200).set_body_string("Base response"))
        .mount(&mock_server)
        .await;

    // Test 1: Use the base behavior
    let response = reqwest::get(&format!("{}/api/base", &mock_server.uri()))
        .await
        .unwrap();
    assert_eq!(response.text().await.unwrap(), "Base response");

    // Test 2: Override the base behavior
    Mock::given(method("GET"))
        .and(path("/api/base"))
        .respond_with(ResponseTemplate::new(200).set_body_string("Overridden response"))
        .mount(&mock_server)
        .await;

    let response = reqwest::get(&format!("{}/api/base", &mock_server.uri()))
        .await
        .unwrap();

    // This assert fails because we get back "Base response"
    assert_eq!(response.text().await.unwrap(), "Overridden response");
}

Is this expected behaviour? If yes, is there some other way to override the base behaviour?

@LukeMathWalker
Copy link
Owner

Yes, this isn't currently supported with an "override" semantic. You can limit how many times the base mock matches, but not much more than that.

@mawkler
Copy link
Author

mawkler commented Oct 28, 2024

I see, thanks for clarifying.

On a side note, thank you very much for writing Zero To Production In Rust! It's an excellent book!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants