3
votes

I am trying to write a unit test which tests a method that uses HttpContext.GetGlobalResourceObject() and I would like to mock it using Moq.

Let's say we're testing this method:

public List<DctmGridColumn> GetDctmColumnsMandatory()
{
   List<DctmGridColumn> metadataFields = new List<DctmGridColumn>
        {
            new DctmGridColumn(HttpContext.GetGlobalResourceObject("SharePoint.Service", "DctmGridColumn_DispName_r_object_id").ToString()),
            new DctmGridColumn(HttpContext.GetGlobalResourceObject("SharePoint.Service", "DctmGridColumn_DispName_object_name").ToString()),
            new DctmGridColumn(HttpContext.GetGlobalResourceObject("SharePoint.Service", "DctmGridColumn_DispName_r_modify_date").ToString()),
            new DctmGridColumn(HttpContext.GetGlobalResourceObject("SharePoint.Service", "DctmGridColumn_DispName_r_version_label").ToString())
        };

        return metadataFields;
}

And this is my test:

[Test]
public void TestGetDctmColumnsMandatory_IsNotNull()
{
    var columns = _viewDefinitionOperations.GetDctmColumnsMandatory();
    Assert.IsNotNull(columns);
}

How can I mock HttpContext? I've been googling the whole day, and I found one or two examples using a mocking framework, the rest creates their own mocks. I've tried to use the approach marked as answer in Setting HttpContext.Current.Session in a unit test, but then I'll have to "replace any calls to HttpContext.Current with HttpContextFactory.Current and have access to the same methods." I'm not that comfortable with that solution.

I'm fairly new to mocking, but I guess there has to be an easier way? I just want to direct all my calls to HttpContext from the unit tests to my mock class. Is that to much to ask? :)

1

1 Answers

1
votes
  1. Have your class under test take a dependency on HttpContextBase (which is abstract).

  2. In normal execution use an HttpContextWrapper (which derives from HttpContextBase) to wrap the HttpContext and supply that to your class.

  3. Then in your unit tests you can pass in a mock HttpContextBase whose GetGlobalResourceObject you control.

It is simple but it requires you to rethink how you design parts of your application. This kind of inversion of control is essential to writing code that's easy to unit test. It may help to use an IoC container.