Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test custom IHttpactionResult

I'm trying to create a custom IHttpActionResult type in web api 2 that will return content as HTML instead of json. What I'm struggling with is how to unit test an ApiController that returns my new ActionResult type. Many example showing how to unit test an ApiController tells you to cast it to OkNegotiatedContentResult and then read the content property off it but this doesn't seem to work in my case. When I debug the test, the code block in ExecuteAsync never seems to be called. Do I need to do this explicitly in my unit tests? Any help would be much appriciated

This is how my ActionResult looks like

public class HtmlActionResult : IHttpActionResult
{
    String _html;
    public HtmlActionResult(string html)
    {
        _html = html;
    }

    public Task<System.Net.Http.HttpResponseMessage> ExecuteAsync(System.Threading.CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StringContent(_html );
        response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/html");
        return Task.FromResult(response);
    }
}

This is my ApiController

public class HomeController : ApiController
{
    public IHttpActionResult Get(string page)
    {
        return new HtmlActionResult("<html></html>");
    }
}

And this is my test method

[TestMethod]
public async Task Get()
{
    //Arrenge
    HomeController controller = new HomeController();

    //Act
    IHttpActionResult result = controller.Get();

    //Assert
    //Assert.IsNotNull(result.Content);
}
like image 680
Abris Avatar asked Oct 23 '25 18:10

Abris


1 Answers

Use Fluent Assertions:

IHttpActionResult result = await controller.Get()

HtmlActionResult htmlActionResult = result.Should()
                                          .BeOfType<HtmlActionResult>()
                                          .Which; // <-- the key feature
                                          // or .And

what means you can nest assertions:

IHttpActionResult result = await controller.Get()

result.Should().BeOfType<HtmlActionResult>()
      .Which.Content.Should().Be(expected);

Or just as @Spock suggested test things separately:

  • Get() returns IHttpActionResult which is actually HtmlActionResult
  • How HtmlActionResult works independently from Get()
like image 157
abatishchev Avatar answered Oct 26 '25 07:10

abatishchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!