views:

18

answers:

1

I'm trying to start using Unit Testing and I want to test the following Controller:

public class AjaxController : Controller {

...

    public JsonResult RateVideo( int userRating, long videoId )
    {

        string userName = User.Identity.Name;

... }

}

I have a created a TestClass with the following method:

[ TestMethod public void TestRateVideo()

    {            

        //Arrange
        AjaxController c = new AjaxController();

        //Act
        JsonResult jr = c.RateVideo(1, 1);



        //Assert
        //Not implemented yet

    }

I select debug and run the test. When the code reaches the 1st statement:

string username = User.Identity.Name;

Debugging stops and I am presented with a message that says that the test failed.

Any guidance you can offer would be appreciated.

A: 

The most common problem testing Controllers is using functions that rely on the HttpContext. The implementation of the User property is something like:

public IPrincipal get_User()
{
    if (this.HttpContext != null)
    {
        return this.HttpContext.User;
    }
    return null;
}

As you can see, User will return null because the HtppContext has not being initialized and calling .Identity will throw an exception. Fortunately MVC lets you set the ControllerContext property so you can create your own instance with a mocked HttpContext.

The MVCContrib project has some test helpers. You can use the TestControllerBuilder in MVCContrib.TestHelper.dll to build your controllers inside your test classes with mocked context.

Ariel Popovsky