如何使用 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).
...
}
我的基本控制器覆盖了获取此 requestContext 的初始化。我正在努力传递这一点,但我没有做正确的事情。
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
}
在哪里可以获得有关使用 Moq 模拟 RequestContext 和 HttpContext 的更多信息?我正在尝试模拟 cookie 和一般上下文。
[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).
...
}
my base controller has an overrride of the Initialize that get's this requestContext. I am trying to pass this along but I am not doing something right.
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
}
Where can I get more information on mocking my RequestContext and HttpContext using Moq? I am trying to mock cookies and the general context.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
HttpContext 是只读的,但它实际上是从 ControllerContext 派生的,您可以对其进行设置。
HttpContext is read-only, but it is actually derived from the ControllerContext, which you can set.
创建请求、响应并将它们都放入 HttpContext:
Create a request, response and put them both to HttpContext:
感谢用户 0100110010101。
它对我有用,在这里我在为以下代码编写测试用例时遇到了问题:
这是解决问题的行
可能对其他人有帮助。
Thanks user 0100110010101.
It worked for me and here i had an issue while writing the testcase for the below code :
And here is the lines which solved the problem
Might be helpful for the others.
以下是我如何使用 ControllerContext 传递假应用程序路径:
Here's how I used the ControllerContext to pass a fake Application path:
以下是如何设置的示例: 模拟 HttpContext HttpRequest 和 HttpResponse for UnitTests(使用 Moq)
请注意真正有助于简化此模拟类的使用的扩展方法:
以下是如何编写单元测试的示例使用起订量检查 HttpModule 是否按预期工作: 使用 Moq 包装 HttpRequest 的 HttpModule 单元测试
更新:此 API 已重构为
Here is an example of how you can set this up: Mocking HttpContext HttpRequest and HttpResponse for UnitTests (using Moq)
Note the extension methods which really help to simplify the usage of this mocking classes:
Here is an example of how to write a Unit Test using moq to check that an HttpModule is working as expected: Unit Test for HttpModule using Moq to wrap HttpRequest
Update: this API has been refactored to