Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

c# - How to unit test an Action method which returns JsonResult?

If I have a controller like this:

[HttpPost]
public JsonResult FindStuff(string query) 
{
   var results = _repo.GetStuff(query);
   var jsonResult = results.Select(x => new
   {
      id = x.Id,
      name = x.Foo,
      type = x.Bar
   }).ToList();

   return Json(jsonResult);
}

Basically, I grab stuff from my repository, then project it into a List<T> of anonymous types.

How can I unit-test it?

System.Web.Mvc.JsonResult has a property called Data, but it's of type object, as we expected.

So does that mean if I want to test that the JSON object has the properties I expect ("id", "name", "type"), I have to use reflection?

EDIT:

Here's my test:

// Arrange.
const string autoCompleteQuery = "soho";

// Act.
var actionResult = _controller.FindLocations(autoCompleteQuery);

// Assert.
Assert.IsNotNull(actionResult, "No ActionResult returned from action method.");
dynamic jsonCollection = actionResult.Data;
foreach (dynamic json in jsonCollection)
{
   Assert.IsNotNull(json.id, 
       "JSON record does not contain "id" required property.");
   Assert.IsNotNull(json.name, 
       "JSON record does not contain "name" required property.");
   Assert.IsNotNull(json.type, 
       "JSON record does not contain "type" required property.");
}

But I get a runtime error in the loop, stating "object does not contain a definition for id".

When I breakpoint, actionResult.Data is defined as a List<T> of anonymous types, so I figure if I enumerate through these, I can check the properties. Inside the loop, the object does have a property called "id" - so not sure what the issue is.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I know I'm a bit late on this guys, but I found out why the dynamic solution wasn't working:

JsonResult returns an anonymous object and these are, by default, internal, so they need to be made visible to the tests project.

Open your ASP.NET MVC application project and find AssemblyInfo.cs from folder called Properties. Open AssemblyInfo.cs and add the following line to the end of this file.

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

Quoted from: http://weblogs.asp.net/gunnarpeipman/archive/2010/07/24/asp-net-mvc-using-dynamic-type-to-test-controller-actions-returning-jsonresult.aspx

I thought it would be nice to have this one for the record. Works like a charm


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...