Unit testing ASP.NET Web API 2 Controller which returns custom result

2.8k views Asked by At

I have a Web API 2 controller which has an action method like this:

public async Task<IHttpActionResult> Foo(int id)
{
    var foo = await _repository.GetFooAsync(id);
    return foo == null ? (IHttpActionResult)NotFound() : new CssResult(foo.Css);
}

Where CssResult is defined as:

public class CssResult : IHttpActionResult
{
    private readonly string _content;

    public CssResult(string content)
    {
        content.ShouldNotBe(null);
        _content = content;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent(_content, Encoding.UTF8, "text/css")
        };

        return Task.FromResult(response);
    }
}

How do i write a unit test for this?

I tried this:

var response = await controller.Foo(id) as CssResult;

But i don't have access to the actual content, e.g i want to verify that the actual content of the response is the CSS i expect.

Any help please?

Is the solution to simply make the _content field public? (that feels dirty)

1

There are 1 answers

0
Andrei Tătar On BEST ANSWER

Avoid casts, especially in unit tests. This should work:

var response = await controller.Foo(id);
var message = await response.ExecuteAsync(CancellationToken.None);
var content = await message.Content.ReadAsStringAsync();
Assert.AreEqual("expected CSS", content);