Skip to content

Configuring a response

Martijn Bodeman edited this page Jul 9, 2022 · 21 revisions

There are several overloads to configure a response. Here are just a few:

mockHttp
    .When(...)
    .Respond(with => with
        .StatusCode(200)
        .Body("text data")
        .ContentType("text/plain", Encoding.UTF8)
    );

mockHttp
    .When(...)
    .Respond((context, cancellationToken) => new HttpResponseMessage(HttpStatusCode.BadRequest));

mockHttp
    .When(...)
    .Respond(with => with
        .StatusCode(200)
        .JsonBody(new Person { FullName = "John Doe" })  // Requires 'skwas.MockHttp.Json' package
        .ContentType("text/plain", Encoding.UTF8)
    )

Throwing an exception

To throw an exception in response to a request:

mockHttp
    .When(...)
    .Throws<InvalidOperationException>();

Configuring response with custom strategy

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.

Setting up a response sequence

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 and only succeed after nth request.
  • scroll/paginating API's which return a subset of a larger list of data

The Respond, RespondUsing, Throws response configuration extensions can be chained to form a sequence.

mockHttp
    .When(...)
    .Respond(with => with.StatusCode(HttpStatusCode.BadGateway))
    .Respond(with => with.ClientTimeout(TimeSpan.FromMilliseconds(500)) // TaskCancelledException after 500 milliseconds
    .Respond(with => with.StatusCode(HttpStatusCode.Ok))
    .Throws<HttpRequestException>()
    .Respond(with => with.StatusCode(HttpStatusCode.Ok))
    .RespondUsing(new MyResponseStrategy())
    .Respond(with => with.StatusCode(HttpStatusCode.Ok))

The last configured response will be repeated if more requests are executed.

Clone this wiki locally