koenmetsu
koenmetsu

Reputation: 1034

Test IHttpActionResult with ExecuteAsync through controller

In short: What's the best way to test a IHttpActionResult through the controller in unit tests?


Given a custom IHttpActionResult with some logic in the ExecuteAsync method

public class AcceptedResult : IHttpActionResult
{
    private readonly Func<string> _ticket;

    public AcceptedResultV2(HttpRequestMessage request, Func<string> ticket)
    {
        _ticket = ticket;
    }

    public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(HttpStatusCode.Accepted);
        response.Headers.Add("x-ticket-id", _ticket());
        return response;
    }
}

and a controller method who exposes a IHttpActionResult

[HttpPost]
public IHttpActionResult Get(SearchScheduledTaskRequest searchScheduledTaskRequest)
{
    if(something) return new AcceptedResult(Request, () => "foo");
    return new AcceptedResult(Request, () => "bar");
}

What is the best way to test this?

At the moment, I've settled for calling ExecuteAsync manually, but it's a bit of a bummer I have to always call ExecuteAsync.

I could of course extract it somewhere, but I'm wondering if there is a better way.

    [TestMethod]
    public async Task Has_Request_Id()
    {
        var response = await _controller.Get(new SearchScheduledTaskRequest()).ExecuteAsync(CancellationToken.None);

        System.Collections.Generic.IEnumerable<string> headers;
        response.Headers.TryGetValues("x-request-id", out headers);
        Assert.AreEqual("foo", headers.First());
    }

Update: made it more clear that I want to test if the controller returns a response with a certain header.

Upvotes: 3

Views: 2942

Answers (1)

Wesley Cabus
Wesley Cabus

Reputation: 121

Based on the provided code, I'd just test if the ExecuteAsync method of the AcceptedResult class returns a response containing the correct headers, because that should always be the case.

Your controller test method just needs to verify whether the result matches the AcceptedResult type.

Upvotes: 1

Related Questions