Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using NUnit and RhinoMocks for unit testing on the (WebApi) project.

There is a method I'm trying to write test for, which is supposed to add an item to HttpContext.Current.Items.

public override void OnActionExecuting(HttpActionContext actionContext)
{
    HttpContext.Current.Items.Add("RequestGUID", Guid.NewGuid());
    base.OnActionExecuting(actionContext);
}

I have no idea how can I make HttpContext.Current.Items available to the method when ran from within a test method. How can I achieve this?

Also, how can I check if the item has been added (what kind of assertion can/should I use)

like image 507
Eedoh Avatar asked Jan 21 '26 03:01

Eedoh


1 Answers

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
like image 108
Old Fox Avatar answered Jan 23 '26 17:01

Old Fox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!