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?
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;
...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With