Unit tests: Anonymous Types and Dynamic

I just saw a chunk of code in Ayende's blog as follows:

public class HomeController : SessionController
    public ActionResult Blog(int id)
        var blog = Session.Get<Blog>(id);

        return Json(new
        }, JsonRequestBehavior.AllowGet);

I like using anonymous types in this fashion and then tests as follows:

dynamic result = ((JsonResult)controller.Blog(1)).Data;

Assert.AreEqual("The subtitle", result.Subtitle);
Assert.AreEqual(1, result.Id);

If you do so, it is not going to work...Why? The quick answer is that anonymous type are internal.

The solution is very simple, edit the AssemblyInfo.cs in the project of the controllers and add the following code:

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

Replace the "MySuperProject.Tests" with the name of your test project.

blog comments powered by Disqus
  • Categories

  • Archives