被测试的Action 包含 User.Identity.Name 代码,在写测试代码需要Mock ControllerContext对象 代码如下:
1 var mock = new Mock<ControllerContext>(); 2 3 mock.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(userName); 4 5 mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true); 6 7 var controller = new DealerStructureController(dsService, null); 8 9 controller.ControllerContext = mock.Object;