4

I have to write a unit test that is testing a controller that happens to be returning JSON as an anonymous type.

The only reason this is anonymous is because I need to add a root node to it, so the return from the controller looks like this:

return Json(new { User = person });

This adds a root node to the JSON with "User", followed by a Person object serialized to JSON.

This works fine, my problem is in the unit test.

The only solution I've seen to testing anonymous types like this is to first make the test project visible using InternalsVisibleTo in AssemblyInfo.cs and then using dynamic to get the results.

    dynamic results = userController.GetPerson(1);
    dynamic content = results.Content;

This fails on the second line, saying that object does not have a Content property. However, under the debugger, it shows the Content property.

How am I supposed to go about testing this?

Error

Content Property

Patrick
  • 5,526
  • 14
  • 64
  • 101

2 Answers2

3

I resolved this issue.

The problem was with the [assembly: InternalsVisibleTo()] attribute.

I had accidentally put this in my unit test project and not in the Web API application where the anonymous type was being returned from the controller.

Adding this to the AssemblyInfo.cs file in the Web API project and using the unit test project name with the attribute resolved the error and the dynamic objects are now populating as expected.

Valid dynamic Content property

Patrick
  • 5,526
  • 14
  • 64
  • 101
0

You can instantiate the dynamic object before calling GetPerson as it is done in here

C# ‘dynamic’ cannot access properties from anonymous types declared in another assembly

Community
  • 1
  • 1
Sudipto Sarkar
  • 346
  • 2
  • 11
  • The results.Content is valid. I can see it in the Visual Studio debugger and it contains a valid object and the properties are set. I can't understand why it is claiming that `object` doesn't contain a `Content` property when we're dealing with a `dynamic` object here, yet if I look at the object in the Visual Studio debugger and expand `Content`, it is all valid. – Patrick Mar 27 '16 at 09:37
  • you can instantiate the dynamic object before calling GetPerson as it is done in here http://stackoverflow.com/questions/2630370/c-sharp-dynamic-cannot-access-properties-from-anonymous-types-declared-in-anot – Sudipto Sarkar Mar 27 '16 at 10:04