问题
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