如何嘲笑HttpContext.User.Identity.Name在Asp.Net MVC 4 [英] How to Mock HttpContext.User.Identity.Name in Asp.Net MVC 4
本文介绍了如何嘲笑HttpContext.User.Identity.Name在Asp.Net MVC 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在消耗控制器code 的HttpContext
I have code in the controller which consumes HttpContext
public ActionResult Index()
{
var currentUser=HttpContext.User.Identity.Name;
......
}
在试图写使用NUnit这样的测试
While trying to write test using NUnit like this
[Test]
public void CanDisplayRequest()
{
//Act
var result= (ViewResult)_requestController.Index();
//Assert
Assert.IsInstanceOf<OrderRequest>(resut.Model);
}
,因为它找不到会导致测试失败的HttpContext
所以,我怎么能嘲笑 HttpContext.Current.User.Identity.Name
推荐答案
您可以初始化与假校长假上下文你的控制器如下图所示。
you can initialize your controller with fake context with fake principal as shown below
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;
这篇关于如何嘲笑HttpContext.User.Identity.Name在Asp.Net MVC 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文