0 Comments

One of the problems that face any web developer is their ability to properly test the GUI components of their sites. A few options exist, specifically Watin, with varying degrees of success. Now that I've been experimenting with the ASP.NET MVC framework I've modified a good deal of my GUI work in such a way that it minimizes form-posts and makes use of the AJAX goodies packed into jQuery. Since a lot of my work has moved to the client following my adoption of this approach I needed to investigate new options for testing. This morning I had the luck to stumble across QUnit, a jQuery testing plugin that makes life pretty easy. 

I won't spend a lot of time explaining how QUnit works. That job has been done already by the jQuery documentation team and in a great tutorial by Chad Myers. I'd encourage you take a look at those links to get a little more familiar with how QUnit works. It's quite simple and elegant, like most other plugins in the jQuery world. What I'll be demonstrating below is how you can use QUnit to unit-test ASP.NET MVC client functionality.

The first example will offer up a much-needed scenario - testing the output of controller methods that return JSON data in the form of JsonResult class instances. The TestJsonMessage() method below exemplifies a typical AJAX request. The client uses jQuery to make the call, the JsonResult is built within the Action method and returned to the client, where it can be accessed in an object-oriented manner via jQuery. 

public JsonResult TestJsonMessage()
{
  return new JsonResult
  {
    Data = new
    {
      Status = true
    }
  };
}

In the View's HTML code JavaScript will be added to perform the test. The TestJsonMessage view is loaded via jQuery's getJSON method. When the data is returned to the client it is used in the actual test code. 

$(document).ready(function()
{
  $.getJSON('/Home/TestJsonMessage', function(data)
  {
    test('TestJsonMessage status should be true', function()
    {
      equals(Boolean(data.Status), true, 'The server should return a status of true');
    });
  });
});

Once the test runs, the output below is generated, indicating the test's success. 

 

This example demonstrates how one might use QUnit to test their MVC actions, specifically those actions that return JSON data to the client. In part 2 of this series I'll provide an example of using QUnit to test changes that might be made to an HTML GUI as a result of MVC actions being called. 

Post comment