How to unit test a method that return an anonymous type?

It’s really easy to have in ASP.NET MVC a function that return an anonymous type. I say in ASP.NET MVC but this could be also in ASP.NET. In fact, when you have an action inside a controller that return a JsonResult you can simply return an anonymous type and Javascript will be able to handle it as simple as using the same syntax that you would use with object in C#.

public JsonResult Update(MyObject o)
{
 //...
 return Json(new { IsSaved = false, Id = 123});
}

In Javascript you would use :

//...Ajax call
 success: function (data) {
   var x = data.IsSaved;
   var xx = data.Id;
}

To unit test this scenario, you need to do two things. First, you need to use the dynamic keyword of .Net to be able to receive from the controller the response of the action which is anonymous.

dynamic returnedData = myController.Update(new MyObject());

The problem is that everything that has been generated as anonymous in a DLL stay internal. If you are doing you unit testing in a separated assembly (DLL) you will need to explicitly say that you want to share internal values with another assembly. This can be done by modifying the assembly configuration by editing AssemblyInfo.cs. You need to open the file AssemblyInfo.cs of the tested controller and add the following statement.

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

This will give the permission to see internal to the unit testing project called “Tests.Unit”.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.