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

谁说我不能喝 提交于 2019-12-01 02:33:50

问题


I want to write a unit test which tests the function of a class called UploadedFile.

The problem I face is this class' static constructor uses HttpContext.Current property and because I am running my unit test from a class library I do not have an HttpContext at the testing time.

Look at my static constructor:

static UploadedFile()
{
    if (HttpContext.Current == null)
        throw new Exception("web server not available");

    HttpServerUtility server = HttpContext.Current.Server;

    // SET UploadedFileMappingFile Names:
    _resourceFileNames = new StringDictionary();

    _resourceFileNames[_suppoertedFileStructures] = server.MapPath(SupportedUploadedFileStructures);
    _resourceFileNames[_supportedFileStructuresXSD] = server.MapPath(SupportedUploadedFileStructuresXSD);

    _resourceFileNames[UploadedFileEnum.UploadedFileFormatENUM.CSV.ToString()] = server.MapPath(UploadedFileColumnMap);        
}

What should I do in my testing environment so that HttpContext.Current won't be null and I can successfully set this:

 HttpServerUtility server = HttpContext.Current.Server;

回答1:


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.



来源:https://stackoverflow.com/questions/3475326/how-can-i-make-httpcontext-available-to-be-used-by-my-unit-tests

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