1

I have a controller in which I am unit testing my Index action. I am having problem in unit testing User.Identity.GetUserId()

This is my controller

public ActionResult Index()
{
   string userId = User.Identity.GetUserId();

   DemoModel demoModel = _demoModelService.GetByUserId(userId);
   MyModel myModel = new MyModel()
      {
            Name = demoModel.Name;
            Description = demoModel.Description;
      }

   return View(myModel);
}



This is my Unit Test:

public void Test_Index_Action()
    {
        //Act
        var result = controller.Index() as ViewResult;

        //Assert
        Assert.AreEqual("", result.ViewName);
    }

When I debug my test method, as it reaches the first line of code(User.Identity.GetUserId) of my Index action, it generates null UserId. How can I access the userId in unit testing this code?

Ruchi
  • 155
  • 1
  • 2
  • 12

1 Answers1

0

I've been struggeling with mvc unit test my self, while there are known techniques to improve testability of your mvc application, most of the projects I worked on are sadly not following them. So I decided to start this project to help me and others who love to unit test their mvc application. Please take a look at: https://github.com/ibrahimbensalah/Xania.AspNet.Simulator.

Here is an example unit test class

using System.Web.Mvc;
using NUnit.Framework;
using Xania.AspNet.Simulator;

public class SimulatorTests
{

    [Test]
    public void ActionExecuteTest()
    {
        // arange
        var controller = new TestController();

        // act
        var result = controller.Execute(c => c.Index());

        // assert
        Assert.AreEqual("Hello Simulator!", result.ViewBag.Title);
    }

    [Test]
    public void UnAuthorizedActionTest()
    {
        // arrange 
        var controller = new TestController();

        // act 
        var result = controller.Execute(c => c.UserProfile());

        // assert
        Assert.IsInstanceOf<HttpUnauthorizedResult>(result.ActionResult);
    }


    [Test]
    public void AuthorizedActionTest()
    {
        // arrange 
        var controller = new TestController();

        // act 
        var result = controller.Action(c => c.UserProfile()).Authenticate("user", null).Execute();

        // assert
        Assert.IsInstanceOf<ViewResult>(result.ActionResult);
    }
}

public class TestController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Title = "Hello Simulator!";
        return View();
    }

    [Authorize]
    public ActionResult UserProfile()
    {
        return View();
    }
}