我想測試我的MVC應用程序,並且我想模擬HttpContext。我使用起訂量框架,這裏是我做了什麼,以模擬的HttpContext:如何在Moq框架中模擬HttpContext(ControllerContext),並有會話
[SetUp]
public void Setup()
{
MyUser myUser = new MyUser();
myUser.Id = 1;
myUser.Name = "AutomatedUITestUser";
var fakeHttpSessionState =
new FakeHttpSessionState(new SessionStateItemCollection());
fakeHttpSessionState.Add("__CurrentUser__", myUser);
ControllerContext mockControllerContext = Mock.Of<ControllerContext>(ctx =>
ctx.HttpContext.User.Identity.Name == myUser.Name &&
ctx.HttpContext.User.Identity.IsAuthenticated == true &&
ctx.HttpContext.Session == fakeHttpSessionState &&
ctx.HttpContext.Request.AcceptTypes ==
new string[]{ "MyFormsAuthentication" } &&
ctx.HttpContext.Request.IsAuthenticated == true &&
ctx.HttpContext.Request.Url == new Uri("http://moqthis.com") &&
ctx.HttpContext.Response.ContentType == "application/xml");
_controller = new SomeController();
_controller.ControllerContext = mockControllerContext; //this line is not working
//when I see _controller.ControllerContext in watch, it get's me
//_controller.ControllerContext threw an exception of type System.ArgumentException
}
[Test]
public void Test_ControllerCanDoSomething()
{
// testing an action of the controller
// The problem is, here, System.Web.HttpContext.Current is null
}
因爲我的應用程序使用會議持有幾乎所有的操作方法,用戶數據和身份驗證信息,因此,我需要設置HttpContext
,在它內部我需要設置Session
並將__CurrentUser__
放在會話中,以便操作方法可以訪問僞造的登錄用戶。
但是,HttpContext
沒有設置,它是空的。我搜索了很多,我找不到我的答案。 什麼可能是錯誤的?
更新: 我也考驗下方線,並得到相同的結果
_controller.ControllerContext = new ControllerContext(
mockControllerContext.HttpContext, new RouteData(), _controller);
可能重複[如何使用Moq模擬ASP.NET MVC中的HttpContext?](http://stackoverflow.com/questions/1452418/how-do-i-mock-the-httpcontext-in-asp -net-mvc-using-moq) –
Microsoft建議在代碼中使用HttpContextWrapper,以便稍後對單元測試進行更簡單的處理.http://msdn.microsoft.com/en-us/library/system.web.httpcontextwrapper(v = vs.110).aspx –
謝謝@MikeCheel但我的問題不同,我沒有設置HttpContext而不是ControllerContext,我的問題是我無法設置ControllerContext!任何人都可以回答我的qiestion嗎? –