Moqing HttpContext

99封情书 提交于 2019-12-11 19:53:26

问题


I have a unit test that tests an MVC controller's result. Unfortunately the controller uses a third party library that uses HttpContext.Request.IsLocal. I cannot refactor the third party library to make it use HttpContextBase.

I need to mock this so that HttpContext.Request.IsLocal returns true. Any Ideas on how to achieve this?


回答1:


If you are using premium or above version of vs2012, try looking at microsoft.fakes. it should cater to your situation.

Some reading:

http://msdn.microsoft.com/en-us/library/hh549175.aspx




回答2:


Although the accepted solution works for you, there are few drawbacks, like dependency on the VS test runner, some problems I read here and there when used with nUnit (or other framework), hard to run these tests with build server like TeamCity, etc.

IMHO the better approach is to isolate the third party lib trough your own shims/wrappers, and not use static methods directly in your code.

Yes, it's a little bit more work, but, it'll be even easier if later you need to upgrade or replace the third party lib - you will be modifying only the wrappers, while your code will not be impacted.



来源:https://stackoverflow.com/questions/18182598/moqing-httpcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!