.netasp.netunit-testinghttpcontexthttpserverutility

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


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;

Solution

  • 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.