-
Notifications
You must be signed in to change notification settings - Fork 4
Configuring a response
skwasjer edited this page Oct 19, 2020
·
21 revisions
There are several overloads to configure a response. Here are just a few:
mockHttp
.When(...)
.Respond(HttpStatusCode.OK, "text data", "text/plain");
mockHttp
.When(...)
.Respond(request => new HttpResponseMessage(HttpStatusCode.BadRequest));
mockHttp
.When(...)
.Respond(async request => await ...);
mockHttp
.When(...)
.RespondJson(new Person { FullName = "John Doe" }) // Requires 'skwas.MockHttp.Json' package
To throw an exception in response to a request:
mockHttp
.When(...)
.Throws<InvalidOperationException>();
For more complex response configurations and/or reusability implement IResponseStrategy
.
public class MyResponseStrategy : IResponseStrategy
{
public Task<HttpResponseMessage> ProduceResponseAsync(MockHttpRequestContext requestContext, CancellationToken cancellationToken)
{
// Custom response logic.
}
}
mockHttp
.When(...)
.RespondUsing(new MyResponseStrategy());
An added benefit is it helps to keep the unit tests themselves clean.
Multiple responses can be configured to form a sequence. This is useful when a request is expected to happen multiple times, but with different responses.
Use cases are for example:
- test resilience by tripping a circuit breaker/retry logic
- scroll/paginating API's
The Respond
, RespondUsing
, RespondJson
, Throws
, TimesOut
, TimesOutAfter
response configuration extensions can be chained to form a sequence.
mockHttp
.When(...)
.Respond(HttpStatusCode.BadGateway)
.TimesOutAfter(500)
.Respond(HttpStatusCode.Ok)
.Throws<HttpRequestException>()
.Respond(HttpStatusCode.Ok)
.RespondUsing(new MyResponseStrategy())
.Respond(HttpStatusCode.Ok)
The last configured response will be repeated if more requests are executed.