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

后端 未结 1 1151
生来不讨喜
生来不讨喜 2021-01-12 22:40

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

1条回答
  •  时光说笑
    2021-01-12 22:50

    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();
    // TODO: Define expectations on the mocked object
    Foo.UploadedFile(contextMock);
    

    Or, if you prefer, use Constructor Injection.

    0 讨论(0)
提交回复
热议问题