使用 Moq 模拟 HttpRequest 时设置 ServerVariable 值?
我正在使用 Moq 模拟 HttpRequest 对象,以在 ASP.NET MVC 中进行单元测试。 我需要在请求中设置 ServerVariables (LOGON_USER) 之一。 这可能吗? 我尝试使用以下方法,但出现异常,因为 ServerVariables 集合是不可覆盖的。
request.SetupGet(req => req.ServerVariables["LOGON_USER"]).Returns(@"TestUserName");
是否可以设置 ServerVariable 值进行测试?
我是否需要传递一个新的 NameValueCollection 而不是尝试设置一个特定的键?
I am mocking an HttpRequest object using Moq for unit testing in ASP.NET MVC. I need to set one of the ServerVariables (LOGON_USER) in the request. Is this possible? I have tried using the following method, but I get an exception because the ServerVariables collection is non-overridable.
request.SetupGet(req => req.ServerVariables["LOGON_USER"]).Returns(@"TestUserName");
Is is possible to set a ServerVariable value for testing?
Do I need to pass in a new NameValueCollection rather than trying to set one specific key?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一种方法。 我通常通过更改规则来模拟这些事情:我不想在测试中了解
HttpRequest
或其相关内容。 相反,我会问:如果我要决定,我可以在哪里获取登录用户的名称?这将是一个
ICallerContext
或我们能想到的任何更好的名称。 然后我改为模拟这个界面。我的控制器需要对新依赖项的引用:
我的测试需要将模拟实例传递给控制器:
That's one way to do it. I usually mock these things by changing the rules: I don't want to know about
HttpRequest
or its relatives in my tests. Instead, I ask: Where can I get the logged on user's name if I were to decide?And that would be an
ICallerContext
or whatever better name we can come up with. Then I mock this interface instead.My controller need a reference to the new dependency:
My test need to pass the mocked instance to the controller:
是的,有可能:
Yes, it is possible:
好的,弄清楚了这一点。 我创建了这个方法来为 ServerVariables 创建 NameValueCollection:
然后我在配置中这样调用它:
Ok, figured this one out. I created this method to create the NameValueCollection for the ServerVariables:
Then I called it like this in my configuration: