scarpacci scarpacci - 3 months ago 75
ASP.NET (C#) Question

IHttpActionResult Anonymous Object - Validate Results

I am trying to create a test for some of our webapi calls and I am having difficulties accessing the results. In all of the examples I have viewed they were using OkNegotiatedContentResult. The problem is that in our web api calls we are often times wrapping the data in anonymous objects so we can combine data sets. I am probably overlooking something obvious, but I can't seem to figure out the proper way to inspect the result information to validate it.

WebApi Snippet

var orderInfo = new
{
Customer = customerInfo,
Order = orderInfo
}

return Ok(orderInfo);


Api Test Snippet

[TestMethod]
public void TestGetOrderInfo()
{
var controller = new OrderController(_repo);
IHttpActionResult results = controller.GetOrderInfo(46);

Assert.IsNotNull(results);


}


How can I inspect the results using the OkNegotiatedContentResult when an anonymous type is involved?

Answer

The reason for the problems with anonymous types is that they are internal types rather than public, so your tests can't use them.

If you add an InternalsVisibleTo attribute to your webapi project you'll then be able to reference the result and its Content via dynamic eg:

[TestMethod]
public void TestGetOrderInfo()
{
    var controller = new OrderController(_repo);
    dynamic results = controller.GetOrderInfo(46);
    dynamic content = results.Content;

    ...

}