35

我在控制器中有代码消耗HttpContext

public ActionResult Index()
{

   var currentUser=HttpContext.User.Identity.Name;
   ......

}

在尝试像这样使用 NUnit 编写测试时

[Test]
public void CanDisplayRequest()
{
    //Act
    var result=  (ViewResult)_requestController.Index();

    //Assert
    Assert.IsInstanceOf<OrderRequest>(resut.Model);
}

测试将失败,因为它找不到HttpContext

那我怎么能嘲笑HttpContext.Current.User.Identity.Name

我正在使用 Moq 进行模拟

4

2 回答 2

55

您可以使用带有假主体的假上下文初始化您的控制器,如下所示

var fakeHttpContext = new Mock<HttpContextBase>();
var fakeIdentity = new GenericIdentity("User");
var principal = new GenericPrincipal(fakeIdentity, null);

fakeHttpContext.Setup(t => t.User).Returns(principal);
var controllerContext = new Mock<ControllerContext>();
controllerContext.Setup(t => t.HttpContext).Returns(fakeHttpContext.Object);

_requestController = new RequestController();

//Set your controller ControllerContext with fake context
_requestController.ControllerContext = controllerContext.Object;
于 2013-09-25T13:42:21.527 回答
4

要仅使用 Microsoft 测试(无 3rd 方框架)来执行此操作,您可以执行以下操作:

public class MockHttpContextBase : HttpContextBase
{
    public override IPrincipal User { get; set; }

}

接着...

        var userToTest = "User";
        string[] roles = null;

        var fakeIdentity = new GenericIdentity(userToTest);
        var principal = new GenericPrincipal(fakeIdentity, roles);
        var fakeHttpContext = new MockHttpContextBase { User = principal };
        var controllerContext = new ControllerContext
        {
            HttpContext = fakeHttpContext
        };

        // This is the controller that we wish to test:
        _requestController = new RequestController();

        // Now set the controller ControllerContext with fake context
        _requestController.ControllerContext = controllerContext;           
于 2018-08-14T05:15:08.333 回答