Question

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?

Was it helpful?

Solution

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;

    ...

}

OTHER TIPS

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.

Patrick found why you are getting error "'object' does not contain a definition for 'Content'". The anonymous type generated by the SUT is internal. Share internals with the test project and you should be able to inspect the anonymous type by doing something like this in the AssemblyInfo.cs in the project: being tested

[assembly: InternalsVisibleTo("Tests.Unit")] 

Found this in article here http://patrickdesjardins.com/blog/how-to-unit-test-a-method-that-return-an-anonymous-type

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top