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)
Avoid casts, especially in unit tests. This should work: