WireMock-Net / WireMock.Net

WireMock.Net is a flexible product for stubbing and mocking web HTTP responses using advanced request matching and response templating. Based on the functionality from http://WireMock.org, but extended with more functionality.
Apache License 2.0
1.35k stars 197 forks source link

Dynamic http status code? #1070

Closed eetawil closed 4 months ago

eetawil commented 4 months ago

Hi, I have this mock setup like this and now I want to also make the status code dynamic (200 or 400) based on the request that I will parse in the "GenerateBody" method, how can I achieve that here?

wireMockServer
                .Given(Request.Create().WithPath("/validatePDFA").UsingPost())
                .RespondWith(Response.Create()                   
                    .WithHeader("Content-Type", "application/json")
                    .WithBody(req => GenerateBody(req))
                    .WithStatusCode(??) 
                    // the "req" returned from the "GenerateBody" could contain the status, but how to retrieve it afterward?
                );
StefH commented 4 months ago

So you are looking for this code?

.WithStatusCode(Func<IRequestMessage, int> statusCodeFactory) 

which can be used like:

.WithStatusCode(req => GenerateStatus(req)) 
eetawil commented 4 months ago

Yes this could work , but I was wondering if there's a way to do it in a single shot?

 .WithBody(req => GenerateBody(req))
.WithStatusCode(??)  <== Use here the result from GenerateBody

Here when generating the body dynamically can it also set the status code without the need of reprocessing the request again?

Or maybe the Objreturned by GenerateBody => Func<IRequestMessage, Obj> could be retrieved and reused in .WithStatusCode ???

StefH commented 4 months ago

In that case. You need "WithCallback".

eetawil commented 4 months ago

Thank you I didn't know about that, I'll look into that. Again, thank you for answering our questions and being available!