views:

86

answers:

2

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.

+1  A: 

IMO, it's better not to test your Ajax methods (I mean client ones, controllers on the server you can test easily) but to test the client's UI. In order to test the UI I recommend you to use Selenium RC or WatiN.

zihotki
+1  A: 

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);
Darin Dimitrov