29

I am very new to unit testing even though i have been coding for a very long time. I want to make this a part of my way of development. I run into blocks on how to unit test things like a collection. I generally have my jQuery script calling ASP.Net Server side methods to get data and populate tables and the like. They look like

Get_*Noun*() 

which generally returns a JsonResult. Any ideas on what and how to test these using Unit tests using MSTest?

6 Answers 6

55

You should be able to test this just like anything else, provided you can extract the values from the JsonResult. Here's a helper that will do that for you:

private T GetValueFromJsonResult<T>(JsonResult jsonResult, string propertyName)
{
    var property =
        jsonResult.Data.GetType().GetProperties()
        .Where(p => string.Compare(p.Name, propertyName) == 0)
        .FirstOrDefault();

    if (null == property)
        throw new ArgumentException("propertyName not found", "propertyName");
    return (T)property.GetValue(jsonResult.Data, null);
}

Then call your controller as usual, and test the result using that helper.

var jsonResult = yourController.YourAction(params);
bool testValue = GetValueFromJsonResult<bool>(jsonResult, "PropertyName");
Assert.IsFalse(testValue);
2
  • Although it's not purely proper to test the results of a transport format, sometimes when building tests around legacy code it's temporarily unavoidable. So this is a good solution. Apr 23, 2012 at 15:46
  • 7
    @MarkFreedman "not purely proper to test the results of a transport format" do you have any references or sources for this claim?
    – Zaid Masud
    Aug 29, 2012 at 12:33
21

(I am using NUnit syntax, but MSUnit shouldn't be far off)

You could test your JsonResult like this:

var json = Get_JsonResult()
dynamic data = json.Data;
Assert.AreEqual("value", data.MyValue)

Then in the project that contains the code to be tested, edit AssemblyInfo.cs file to allow the testing assembly access to the anonymous type:

[assembly: InternalsVisibleTo("Tests")]

This is so the dynamic can determine the type of anonymous object being returned from the json.Data value;

3
  • 4
    Just to clarify: [assembly: InternalsVisibleTo("TestProjectNamespace")] should be set at MVC AssemblyInfo.cs project. Jul 6, 2012 at 19:30
  • Also to clarify, the assembly directive goes in the project that has the code being tested and not in the test project itself.
    – rboarman
    Feb 6, 2015 at 4:35
  • Not sure if this has changed since this question has answered but compiler will complain that the 'InternalsVisibleTo' attribute requires a strong assembly name (signed). That complicates things quite a bit. Oct 21, 2015 at 0:45
3

This is the best blog I've found on this subject.

My favorite was the 4th approach using dynamics. Note that it requires you to ensure that the internals are visible to your test project using [assembly:InternalsVisibleTo("TestProject")] which I find is a reasonably good idea in general.

[TestMethod]     
public void IndexTestWithDynamic()     
{     
    //arrange     
    HomeController controller = new HomeController();     

    //act     
    var result = controller.Index() as JsonResult;     

    //assert     
    dynamic data = result.Data;  

    Assert.AreEqual(3, data.Count);     
    Assert.IsTrue(data.Success);     
    Assert.AreEqual("Adam", data.People[0].Name);     
}
2
  • Why dynamic? the .Data property is of type object holding for example a List<Person>. The result.Data can be casted to List<Person>...
    – Elisabeth
    Sep 9, 2012 at 18:20
  • 2
    @Elisa the underlying assumption in this thread has been that contents of the .Data property is an anonymous type.
    – Zaid Masud
    Sep 9, 2012 at 19:15
2

You could use PrivateObject to do this.

var jsonResult = yourController.YourAction(params);
var success = (bool)(new PrivateObject(jsonResult.Data, "success")).Target;
Assert.IsTrue(success);

var errors = (IEnumerable<string>)(new PrivateObject(jsonResult.Data, "errors")).Target;
Assert.IsTrue(!errors.Any());

It's uses reflection similar to David Ruttka's answer, however it'll save you a few key strokes.

See http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privateobject.aspx for more info.

0

Here's a small extension to easily convert a Json ActionResult into the object it represents.

using System.Web.Mvc;

public static class WebExtensions
{
     public static T ToJson<T>(this ActionResult actionResult)
     {
         var jsonResult = (JsonResult)actionResult;

         return (T)jsonResult.Data;
     }
}

With this, your 'act' in the test becomes smaller:

var myModel = myController.Action().ToJson<MyViewModel>();
0
0

My suggestion would be to create a model for the data returned and then cast the result into that model. That way you can verify:

  1. the structure is correct
  2. the data within the model is correct

    // Assert
    var result = action
        .AssertResultIs<JsonResult>();
    
    var model = (UIDSearchResults)result.Data;
    Assert.IsTrue(model.IsValid);
    Assert.AreEqual("ABC", model.UIDType);
    Assert.IsNull(model.CodeID);
    Assert.AreEqual(4, model.PossibleCodes.Count());
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.