How can I make HttpContext available to be used by my Unit Tests?

风格不统一 提交于 2019-12-01 04:48:31
Darin Dimitrov

You shouldn't use HttpContext.Current directly in your function as it is close to impossible to unit test, as you've already found out. I would suggest you using HttpContextBase instead, which is passed either in the constructor of your class or as an argument to the method you are testing. This will allow the consumers of this class to pass a real HttpContextWrapper and in your unit test you can mock the methods you need.

For example here's how you could call the method:

var wrapper = new HttpContextWrapper(HttpContext.Current);
Foo.UploadedFile(wrapper);

And in your unit test (using Rhino Mocks):

var contextMock = MockRepository.GenerateMock<HttpContextBase>();
// TODO: Define expectations on the mocked object
Foo.UploadedFile(contextMock);

Or, if you prefer, use Constructor Injection.

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