Moqing HttpContext.Current
我有一个类库,其中有一个基于模板发送电子邮件的方法。我通过以下方式访问模板:
HttpContext.Current.Server.MapPath("email template path");
现在,在编写单元测试时,我希望能够模拟“当前上下文”,我尝试使用 MVCMockHelpers,但“当前”属性始终返回 null。
是否可以模拟这个属性?如果是这样我该怎么办?
I have a class library that has a method that sends emails based on a template. I access the template via the following:
HttpContext.Current.Server.MapPath("email template path");
Now when it comes to writing my unit tests I want to be able mock out the "Current Context", I have tried to use the MVCMockHelpers but the "Current" property always returns null.
Is it possible to mock this property out? If so how do I go about it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

我会考虑是否最好完全删除对 HttpContext 的依赖并将路径作为字符串参数单独传递到方法中。
如果您还在同一库中的其他位置依赖于 HttpContext,那么您需要依赖于 HttpContextBase 而不是直接调用 HttpContext。您应该将其传递到调用站点或作为构造函数注入参数。
许多其他人都很好地介绍了创建模拟 HttpContext,包括此处克雷格·斯图茨.这至少可以帮助您入门,但可能需要根据您的特定测试要求进行修改。
I'd consider whether you'd be better of removing the dependency on HttpContext entirely and pass the path alone into the method as a string param.
If you're also taking a dependency on HttpContext elsewhere in the same library then you need to take a dependency on HttpContextBase rather than call HttpContext directly. You should pass this in at the call site or as a constructor injected parameter.
Creating a Mock HttpContext has been covered nicely by many others including here by Craig Stuntz. This will at least get you started but will likely needed modification for your specific testing requirements.