简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM