lundi 11 janvier 2016

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 NotFound();
    return new AcceptedResult(Request, () => "foo");
}

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(_expectedTicket, headers.First());
    }

Aucun commentaire:

Enregistrer un commentaire