如何使用Moq在ASP.NET MVC中模拟HttpContext?[TestMethod]public void Home_Message_Display_Unknown_User_when_coockie_does_not_exist(){
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
context .Setup(c => c.Request)
.Returns(request.Object);
HomeController controller = new HomeController();
controller.HttpContext = context; //Here I am getting an error (read only).
...
}我的基本控制器有一个重写的Initialize,它得到了这个requestContext。我试图通过这个,但我没有做正确的事情。protected override void Initialize(System.Web.Routing.RequestContext requestContext){
base.Initialize(requestContext);}在哪里可以获得有关使用Moq模拟我的RequestContext和HttpContext的更多信息?我正在尝试模拟cookie和一般上下文。
3 回答
慕少森
TA贡献2019条经验 获得超9个赞
HttpContext是只读的,但它实际上是从您可以设置的ControllerContext派生的。
controller.ControllerContext = new ControllerContext( context.Object, new RouteData(), controller );
回首忆惘然
TA贡献1847条经验 获得超11个赞
创建一个请求,响应并将它们都放到HttpContext中:
HttpRequest httpRequest = new HttpRequest("", "http://mySomething/", "");
StringWriter stringWriter = new StringWriter();
HttpResponse httpResponse = new HttpResponse(stringWriter);
HttpContext httpContextMock = new HttpContext(httpRequest, httpResponse);
素胚勾勒不出你
TA贡献1827条经验 获得超9个赞
它对我有用,在这里我在为下面的代码编写测试用例时遇到了问题:
var currentUrl = Request.Url.AbsoluteUri;
以下是解决问题的方法
HomeController controller = new HomeController();//Mock Request.Url.AbsoluteUri HttpRequest httpRequest = new HttpRequest("", "http://mySomething", "");StringWriter stringWriter = new StringWriter();HttpResponse httpResponse = new HttpResponse(stringWriter);HttpContext httpContextMock = new HttpContext(httpRequest, httpResponse);controller.ControllerContext = new ControllerContext(new HttpContextWrapper(httpContextMock), new RouteData(), controller);
可能对其他人有帮助。
- 3 回答
- 0 关注
- 771 浏览
添加回答
举报
0/150
提交
取消