Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unit test my Json result in an ASP.NET MVC3 web site?

I'm trying to test the Data values that are returned from an ASP.NET MVC3 JsonView, but I'm not sure how.


I have a simple ASP.NET MVC3 website, with an action method that returns a JsonView.

eg (some pseduo code for a list of anonymous types):

var lotsOfFail = database.GetMeThatDamnDataList();
var returnData = (from x in lotsOfFail
                  select new
                  {
                      Id = x.Id,
                      Name = x.Name
                      ..
                   }).ToList();
return Json(returnData, JsonRequestBehavior.AllowGet);

Now in my unit test, I'm trying to test the values of Data. So following various suggestions, I'm doing the following.. which -does- work :-

// Act.
JsonResult jsonResult = controller.PewPewKThxBai(null, null);

// Assert.    
Assert.IsNotNull(jsonResult);
dynamic data = jsonResult.Data;
Assert.IsNotNull(data);
Assert.IsTrue(data.Count >= 0);

But I also wish to test the first three results that come back, against a fixed list of data.

Notice how I have the following code: var lotsOfFail = database.GetMeThatDamnDataList(); Well, the database is populated with some hardcoded data AND some random data. The first three records are hardcoded.

As such, I wish to make sure that I can test my hardcoded data.

Like this...

// Assert.    
Assert.IsNotNull(jsonResult);
dynamic data = jsonResult.Data;
Assert.IsNotNull(data);

var hardCodedData =
    FakeWhatevers.CreateHardcodedWhatevers()
    .Where(x => x.EventType == EventType.BannableViolation)
    .ToList();
Assert.IsTrue(data.Count >= hardCodedData .Count);

for (int i = 0; i < hardCodedData .Count; i++)
{
    Assert.AreEqual(data[0].Id== hardCodedData [0].GameServerId);
}

but because data is a dynamic, I don't know how to test the properties of it.

Any ideas?

like image 234
Pure.Krome Avatar asked Nov 01 '11 05:11

Pure.Krome


1 Answers

The following should work:

for (int i = 0; i < hardCodedData.Count; i++)
{
    Assert.AreEqual(hardCodedData[i].GameServerId, data[i].Id);
    Assert.AreEqual(hardCodedData[i].GameServerName, data[i].Name);
    ...
}

Notice that I have inverted the order of argument as the first is the expected and the second is the actual.

like image 118
Darin Dimitrov Avatar answered Sep 20 '22 14:09

Darin Dimitrov