如何模拟 ASP.NET ServerVariables[“HTTP_HOST”] 值?
我有以下代码,在运行时失败...
var mock = new Mock<ControllerContext>();
mock.SetupGet(x => x.HttpContext.Request
.ServerVariables["HTTP_HOST"]).Returns(domain);
** 运行时错误:不可覆盖的设置无效 财产
我的控制器中有一些代码,它需要检查用户请求/访问的域。
我不知道如何模拟它?有什么想法吗?
附言。我在上面的例子中使用了 Moq 框架..所以我不确定这是否是一个问题,等等?
i have the following code, which fails during runtime...
var mock = new Mock<ControllerContext>();
mock.SetupGet(x => x.HttpContext.Request
.ServerVariables["HTTP_HOST"]).Returns(domain);
** RunTime Error: Invalid setup on non-overridable
property
I've got some code in my controller, which needs to check the domain the user has requested/gone to.
I'm not sure how to mock it up? any ideas?
PS. I'm using the Moq framewoke in the above example .. so I'm not sure if that's an issue, etc.?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法模拟 NameValueCollection 上的索引器,因为它不是虚拟的。我要做的是模拟 ServerVariables 属性,因为它是虚拟的。您可以填写自己的NameValueCollection。见下文
这是我要做的:
You can't mock the indexer on a NameValueCollection because it's not virtual. What I would do is mock the ServerVariables property since that IS virtual. You can fill in your own NameValueCollection. See below
Here's what I would do:
您可以使用接口覆盖 HttpContext 并在测试中模拟它:
然后在控制器代码中使用 HttpContextValues 而不是 ControllerContext.HttpContext。您不必对模拟进行任何组合。
You can cover HttpContext with interface and mock it in your tests:
Then you use HttpContextValues instead of ControllerContext.HttpContext in your controller code. You don't have to make any combinations about mocking.