Unit Testing An ASP.NET Web API 2 controller that returns a custom result

I have a Web API 2 controller that has a mode of action similar to 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 to write 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, for example, I want to check that the actual content of the response is the expected CSS.

Any help please?

Is the solution just to make the _content field public? (which feels dirty)

+5
source share
1 answer

Avoid castings, 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); 
+2
source

All Articles