Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you unit test your ASP.Net MVC JsonResult actions?

I'm still figuring out a few of the finer points around unit testing my ASP.Net MVC2 application using NUnit.

On the whole, testing my ActionResults, models, respositories and the like is straight-forward, but I've not had to test Ajax methods before and I'd like some guidance on how I should best go about it.

Thanks in advance.

like image 749
Phil.Wheeler Avatar asked Mar 04 '10 09:03

Phil.Wheeler


People also ask

How do I assert JsonResult?

We can return jsonResult via invoking the Josn() method in the controller, in general, I will pass one anonymous object such as Josn(new {isSuccess = true, message="It's success!"}); var actionResult = controller. JosnMethod() as JsonResult; Assert.

What is JsonResult in ASP NET MVC?

Json(Object, String, Encoding, JsonRequestBehavior) Creates a JsonResult object that serializes the specified object to JavaScript Object Notation (JSON) format using the content type, content encoding, and the JSON request behavior.


1 Answers

Testing a controller action returning a JsonResult shouldn't be any different of testing other actions. Consider the following scenario:

public class MyModel
{
    public string Name { get; set; }
}

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return Json(new MyModel { Name = "Hello World" });
    }
}

And the unit test (sorry it's MSTest, I don't have NUnit atm but it should be pretty strait forward):

// arrange
var sut = new HomeController();

// act
var actual = sut.Index();

// assert
Assert.IsInstanceOfType(actual, typeof(JsonResult));
var jsonResult = (JsonResult)actual;
Assert.IsInstanceOfType(jsonResult.Data, typeof(MyModel));
var model = (MyModel)jsonResult.Data;
Assert.AreEqual("Hello World", model.Name);
like image 142
Darin Dimitrov Avatar answered Sep 25 '22 17:09

Darin Dimitrov