Mocking User.Identity in ASP.NET MVC

后端 未结 6 913
眼角桃花
眼角桃花 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:00

    To mock WindowsIdentity you can do the following:

    var mockedPrincipal = new Mock(WindowsIdentity.GetCurrent());
    
    mockedPrincipal.SetupGet(x => x.Identity.IsAuthenticated).Returns(true);
    mockedPrincipal.SetupGet(x => x.Identity.Name).Returns("Domain\\User1");
    mockedPrincipal.Setup(x => x.IsInRole("Domain\\Group1")).Returns(true);
    mockedPrincipal.Setup(x => x.IsInRole("Domain\\Group2")).Returns(false);
    

    then use mockedPrincipal.Object to get the actual WindowsIdentity

提交回复
热议问题