alexliesenfeld / httpmock

HTTP mocking library for Rust.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to mock the same endpoint but return different requests

simonrw opened this issue · comments

I am trying to mock requests to a status endpoint that's polled. The endpoint returns the status of a job. I want to test my logic that I poll the endpoint until the job is complete.

How would I go about doing this?

I have tried:

  1. adding multiple then statements, but methods on then take self by value and so then calls can't be repeated.
  2. adding multiple server.mock(|when, then| { statements, but the mock seems to only return the first one.

Hi!

httpmock matches requests to mock specs in the order they were created. So you could do as follows:

  1. Create two mocks for the same endpoint. The first mock with a "not finished" response, the second with a "finished" response. Store the mock reference of the first mock for future use (see link to example below).
  2. Once your job is "complete", use Mock.delete to delete the first mock from the mock server.
  3. Thereafter, httpmock will respond with data from the mock you created second.

There is this deletion example in the tests directory.

Does this help?

Thanks @alexliesenfeld that does help. I want to test a high level poll method, so deleting the mocks in between iterations might be tricky, but that's a problem for me to sort. Thanks for your help.