1

I am trying to just return a very simple Anonymous object as Json like so:

    [HttpGet]
    public JsonResult GetJson()
    {
        return Json(new {
            id = 1,
            child = new
            {
                id = 12, 
                name = "woop woop"
            } 
        });
    }

Then I have a test case that verify that id = 1

    [TestMethod]
    public void TestMethod4()
    {
        var controller = new ValuesController();
        dynamic result = controller.GetJson();

        Assert.AreEqual(1, result.Value.id);
    }

This result in:

Message: Test method UnitTestProject1.UnitTest1.TestMethod4 threw exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'id'

Image from VS

ganjan
  • 7,356
  • 24
  • 82
  • 133

1 Answers1

3

Your method returns a JsonResult which contains a property Data which is your object, so your code should be

[TestMethod]
public void TestMethod4()
{
    var controller = new ValuesController();
    dynamic result = controller.GetJson().Data; // returns { id = 1, child = new { id = 12, name = "woop woop" } }
    Assert.AreEqual(1, result.id);
}

However anonymous objects are internal so you also need to make your object visible to your test project. In the AssemblyInfo.cs file of the project containing the ValuesController class, add

[assembly: InternalsVisibleTo("YourProjectName.UnitTestProject1")]
  • nice answer. Will be helpful for others also – Arunprasanth K V Oct 11 '17 at 09:52
  • The GetJson() does not have .Data, it has .Value. I don't have any AssemblyInfo.cs file. It's a .Net Core 1.1 project. – ganjan Oct 11 '17 at 10:16
  • Then tag your question properly! –  Oct 11 '17 at 10:16
  • Refer [this answer](https://stackoverflow.com/questions/42138418/equivalent-to-assemblyinfo-in-dotnet-core-csproj/42183749) for the equivalent of `AssemblyInfo.cs` –  Oct 11 '17 at 10:18
  • Also [this answer](https://stackoverflow.com/questions/40286152/project-json-equivalent-of-internalsvisibleto) –  Oct 11 '17 at 10:24