单元测试user.identity.getuserid asp.net mvc

时间:2014-11-17 11:42:19

标签: asp.net-mvc 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);
    }

当我调试我的测试方法时,当它到达我的Index操作的第一行代码(User.Identity.GetUserId)时,它会生成null UserId。如何在单元测试此代码时访问userId?

1 个答案:

答案 0 :(得分:0)

我一直在用自己的mvc单元测试,虽然有一些已知的技术来提高你的mvc应用程序的可测试性,但我工作的大多数项目都很遗憾没有遵循它们。 所以我决定启动这个项目来帮助我和其他喜欢对他们的mvc应用程序进行单元测试的人。请查看:https://github.com/ibrahimbensalah/Xania.AspNet.Simulator

这是一个示例单元测试类

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();
    }
}