How to mock HttpContext.Current.Items with NUnit and Rhino Mocks

孤街浪徒 提交于 2019-12-06 22:14:33

You don't need to refactor your code\use RhinoMocks at all for testing it.

Your UT should be similar to the following example:

[Test]
public void New_GUID_should_be_added_when_OnActionExecuting_is_executing()
{
    //arrange section:
    const string REQUEST_GUID_FIELD_NAME = "RequestGUID";

    var httpContext = new HttpContext(
        new HttpRequest("", "http://google.com", ""),
        new HttpResponse(new StringWriter())
    );

    HttpContext.Current = httpContext;

    //act:
    target.OnActionExecuting(new HttpActionContext());

    //assert section:
    Assert.IsTrue(HttpContext.Current.Items.Contains(REQUEST_GUID_FIELD_NAME));
    var g = HttpContext.Current.Items[REQUEST_GUID_FIELD_NAME] as Guid?;
    if (g == null)
    {
        Assert.Fail(REQUEST_GUID_FIELD_NAME + 
                    " is not a GUID, it is :: {0}", 
                    HttpContext.Current.Items[REQUEST_GUID_FIELD_NAME]);
    }
    Assert.AreNotEqual(Guid.Empty, g.Value);
}

BTW, you can split this test to 2:

  1. verifies that the RequestGUID is being populated with a GUID
  2. verifies that the GUID is not Guid.Empty
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!