Mocking User.Identity in ASP.NET MVC

后端 未结 6 886
眼角桃花
眼角桃花 2020-12-13 06:23

I need to create Unit Tests for an ASP.NET MVC 2.0 web site. The site uses Windows Authentication.

I\'ve been reading up on the necessity to mock the HTTP context

6条回答
  •  醉梦人生
    2020-12-13 07:25

    Example for mocking username and SID on MVC4. The username and SID (Windows Authentication) in the following action should be tested:

    [Authorize]
    public class UserController : Controller
    {
        public ActionResult Index()
        {
            // get Username
            ViewBag.Username = User.Identity.Name;
    
            // get SID
            var lIdentity = HttpContext.User.Identity as WindowsIdentity;
            ViewBag.Sid = lIdentity.User.ToString();
    
            return View();
        }
    }
    

    I use Moq and Visual Studio Test Tools. The test is implemented as follows:

    [TestMethod]
    public void IndexTest()
    {
        // Arrange
        var myController = new UserController();
        var contextMock = new Mock();
        var httpContextMock = new Mock();
        var lWindowsIdentity = new WindowsIdentity("Administrator");
    
        httpContextMock.Setup(x => x.User).Returns(new WindowsPrincipal(lWindowsIdentity));
    
        contextMock.Setup(ctx => ctx.HttpContext).Returns(httpContextMock.Object);
        myController.ControllerContext = contextMock.Object;
    
        // Act
        var lResult = myController.Index() as ViewResult;
    
        // Assert
        Assert.IsTrue(lResult.ViewBag.Username == "Administrator");
        Assert.IsTrue(lResult.ViewBag.Sid == "Any SID Pattern");
    }
    

提交回复
热议问题