Mocking HttpContext.GetGlobalResourceObject in NUnit with Moq

匿名 (未验证) 提交于 2019-12-03 08:57:35

问题:

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



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