Skip to content

Configuring a response

Martijn Bodeman edited this page Dec 19, 2023 · 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>();

Simulating latency

To simulate network latency, there are a few options.

Latency extension

The simplest method is to just introduce an artificial delay using the Latency() extension. When the request is sent and handled by the mock handler, it will then wait using a Task.Delay() for the specified amount of time, before returning the configured response.

using static MockHttp.NetworkLatency;

mockHttp
    .When(...)
    .Respond(with => with
        .StatusCode(200)
        .Latency(ThreeG)
    );

// Or some of the other overloads, like:
mockHttp
    .When(...)
    .Respond(with => with
        .StatusCode(200)
        .Latency(Around(TimeSpan.FromMilliseconds(100)))
    );

For convenience, I included several helpful functions which adds some variance to the latency (OneG, TwoG, ThreeG, FourG and FiveG), but you can also specify the delay with TimeSpans using Around() and Between().

Rate limiting the response data

Alternatively, we can also simulate slow network transfer rates. This does however require that you provide a stream and wrap it in a RateLimitedStream. The RateLimitedStream will limit the amount of bytes that can be read by the specified bit rate.

using Stream stream = ...; // A big stream

mock.When(...)
    .Respond(with => with
        .Body(() => new RateLimitedStream(stream, 512000)) // Rate limited to 512 kbps
    );

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