justeattakeaway / httpclient-interception

A .NET library for intercepting server-side HTTP requests
https://tech.just-eat.com/2017/10/02/reliably-testing-http-integrations-in-a-dotnet-application/
Apache License 2.0
339 stars 27 forks source link

Response sequence #507

Open robert-bialy opened 1 year ago

robert-bialy commented 1 year ago

I would like to have an option to setup a sequence of responses for certain request. It would certainly help with testing retry policies.

Describe the solution you'd like

Moq allows for user to setup a sequence of responses like:

consumerService.SetupSequence(c => c.Consume(It.IsAny<CancellationToken>()))
    .Returns(payload)
    .Throws<OperationCanceledException>()
    .Returns(payload);

It would be great if we would be able to do the same in this library:

builder
    .Requests()
    .ForPost()
    .ForHttps()
    .ForHost(host)
    .ForPath(endpoint)
    .RespondsInSequence()
        .WithStatus(HttpStatusCode.InternalServerError)
    .Then()
        .WithStatus(HttpStatusCode.InternalServerError)
    .Then()
        .WithStatus(HttpStatusCode.OK)
    .RegisterWith(options);
martincostello commented 1 year ago

Thanks for the suggestion.

This is possible today, albeit not with a Moq-like syntax.

Using the latest available release, you can do something like this:

https://github.com/justeat/httpclient-interception/blob/7216d7cb0237f944c2681aa0db1d81776a1b0d28/tests/HttpClientInterception.Tests/Examples.cs#L698-L757

In the next release, this can be simplified a bit using the new ForAll() method:

https://github.com/justeat/httpclient-interception/blob/2558c1d25498a1160caf6f34fa59e31ba3f29f94/tests/HttpClientInterception.Tests/Examples.cs#L698-L756

I'll leave this open for us to consider if there's a relatively low-effort way we could achieve an API similar to what you suggested with some additional extension methods or similar in a future release.