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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With