WireMock.Net icon indicating copy to clipboard operation
WireMock.Net copied to clipboard

Dynamic http status code?

Open eetawil opened this issue 2 years ago • 4 comments

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?
                );

eetawil avatar Feb 26 '24 14:02 eetawil

So you are looking for this code?

.WithStatusCode(Func<IRequestMessage, int> statusCodeFactory) 

which can be used like:

.WithStatusCode(req => GenerateStatus(req)) 

StefH avatar Mar 02 '24 15:03 StefH

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 Obj returned by GenerateBody => Func<IRequestMessage, Obj> could be retrieved and reused in .WithStatusCode ???

eetawil avatar Mar 04 '24 20:03 eetawil

In that case. You need "WithCallback".

StefH avatar Mar 04 '24 21:03 StefH

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

eetawil avatar Mar 05 '24 13:03 eetawil