lipanski / mockito

HTTP mocking for Rust!

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Help: Cannot migrate to v1

ymwjbxxq opened this issue · comments

commented

Hello all,

currently, I am using version mockito = "0.31" and my unit tests are passing

//CODE
...
        #[cfg(not(test))]
        let uri = format!(
            "{search_domain}/{search_index}/_search?size={page_size}&pretty=true",
            page_size = PAGE_SIZE,
            search_domain = &self.search_domain,
            search_index = &self.search_index
        );
        #[cfg(test)]
        let uri = format!("{}/endpoint", mockito::server_url());
...

//UNIT TEST
....
// ARRANGE
        let _m = mock("GET", "/endpoint")
            .with_header("content-type", "application/json")
            .with_body("{\"took\": 11,\"timed_out\": false,\"_shards\": {\"total\": 5,\"successful\": 5,\"skipped\": 0,\"failed\": 0},\"hits\": {\"total\": {\"value\": 1,\"relation\": \"eq\"},\"max_score\": 6.875992,\"hits\": [{\"_index\": \"shortener-stage\",\"_id\": \"07097514-4ec3-53e6-8d12-daa4f969bfcd\",\"_score\": 6.875992,\"_source\": {\"path\": \"/ciao\",\"target\": \"https://ciao.com\"}}]}}")
            .create();

If I convert to v1 in this way:

        #[cfg(test)]
        let uri = format!("{}/endpoint", mockito::Server::new().url());

I get this error:
reqwest sdk error reqwest::Error { kind: Decode, source: Error(\"EOF while parsing a value\"

Could you please help me to understand what the problem is? Do you know if I miss a configuration?

Thanks,
Dan

You have to hold a reference to mockito::Server and use that to create your mocks and call .url():

let mut server = mockito::Server::new();
server.mock("GET", "/endpoint").with_body("hello").create();

#[cfg(test)]
let uri = format!("{}/endpoint", server.url());

These days, every server can have its own URL and mocks.

See the migration instructions or the docs for more details.

commented

@lipanski thank you but can you clarify is there any way to statically refer to the URL? If all endpoints are isolated by path (not port) couldn't it be static and parallel tests wouldn't stomp each other so long as they used different paths?

I have given up trying to find ways to do it and all of my production code has an additonal argument url_override that allows my unit tests to inject the mock endpoint. But this hurts readability so I'm wondering if there's a cleaner way?

env vars are globally shared (so parallel tests will stomp each other), holding static reference to ServerGuard is unsafe, running tests serially is slow... Any other ideas?