views:

41

answers:

2

Hi,

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;
+6  A: 

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 argument to the method you are testing. This will allow you consumers of this class to pass a real HttpContextWrapper and in your unit test mock the methods you need.

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

var context = 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.

Darin Dimitrov
@Darin: Thanks for the idea! I have not used Rhino.Mocks.dll so far unfortunately. It seems I have to get familiar with it first then I will try to implement your suggestion. Thanks!
burak ozdogan
A: 

I think this Stackoverflow question can be helpful as well: http://stackoverflow.com/questions/1214178/moq-unit-testing-a-method-relying-on-httpcontext

burak ozdogan