Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 816
scarpacci Avatar asked Mar 18 '14 17:03

scarpacci


2 Answers

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;

    ...

}
like image 173
Graeme Bradbury Avatar answered Oct 05 '22 23:10

Graeme Bradbury


Anonymous objects are internal to the assembly that created them. If you are doing unit testing in a separated assembly (DLL) you will need to explicitly say that you want to share internal values with that assembly using the InternalsVisibleTo attribute.

like image 28
Corey Ford Avatar answered Oct 05 '22 22:10

Corey Ford