Anonymous IHttpActionResult object - checking results

I'm trying to create a test for some of our webapi calls, and I'm having difficulty accessing the results. In all the examples I looked at, they used OkNegotiatedContentResult. The problem is that in our web api calls we often rewind data into anonymous objects so that we can combine datasets. I probably don’t notice anything obvious, but I can’t figure out how to correctly check the result information in order to verify 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 to check results using OkNegotiatedContentResult when an anonymous type is used?

+8
c # anonymous-types asp.net-web-api
source share
3 answers

The reason for the problems with anonymous types is that they are internal types, not public types, so your tests cannot use them.

If you add the InternalsVisibleTo attribute to your webapi project, you can reference the result and its contents through a dynamic one, for example:

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

Anonymous objects are internal to the assembly that created them. If you are doing unit testing in a separate assembly (DLL), you need to explicitly indicate that you want to share internal values ​​with this assembly using the InternalsVisibleTo attribute.

+2
source

Patrick found why you get an error. "Object" does not contain a definition for "Content". The anonymous type created by SUT is internal. Share the insides with the test project and you can check the anonymous type by doing something like this in AssemblyInfo.cs in the project: being tested

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

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

+1
source

All Articles