Skip to content

Unable to override mock behaviour #150

@mawkler

Description

@mawkler

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions