Mocking User.Identity in ASP.NET MVC

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

    I don't know for MVC 2.0, but in newer versions you can mock the ControllerContext:

    // create mock principal
    var mocks = new MockRepository(MockBehavior.Default);
    Mock mockPrincipal = mocks.Create();
    mockPrincipal.SetupGet(p => p.Identity.Name).Returns(userName);
    mockPrincipal.Setup(p => p.IsInRole("User")).Returns(true);
    
    // create mock controller context
    var mockContext = new Mock();
    mockContext.SetupGet(p => p.HttpContext.User).Returns(mockPrincipal.Object);
    mockContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);
    
    // create controller
    var controller = new MvcController() { ControllerContext = mock.Object };
    

    see also How to unit-test an MVC controller action which depends on authentification in c#?

提交回复
热议问题