Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock HttpContext.Current.GetOwinContext() with Nunit and RhinoMocks?

Compared to my last question on Mocking the HttpContext, I had to change the method being tested to

public override void OnActionExecuting(HttpActionContext actionContext)
{
    HttpContext.Current.GetOwinContext().Set("RequestGUID", NewId.NextGuid());
    base.OnActionExecuting(actionContext);
}

Now I need to figure out how to mock the HttpContext.Current.GetOwinContext(), So I could write a stub for the Set() method, or generally being able to test this particular line. How can I do this?

like image 229
Eedoh Avatar asked Jul 25 '17 14:07

Eedoh


1 Answers

I have read this article, but in your case, I think that doing such a thing would be an overkill..

Since GetOwinContext() return an interface all you have to do is to separate this call from the method, doing such a thing has 2 problems:

  1. The method under test(OnActionExecuting() is owned by an attribute class.
  2. GetOwinContext() is a static method.

The best 2 solutions that I can offer you is:

  1. Use code waving tool like MsFakes, Typemock Isolator and etc, instead of proxy based tool like RhinoMocks.
  2. Extract GetOwinContext() to a virtual method and then use PartialMock technique(This technique is usually in use for abstract classes):

Let's say that MyCustonAttributte is your attribute:

public class MyCustonAttributte : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        GetOwinContext().Set("RequestGUID", Guid.NewGuid());
        base.OnActionExecuting(actionContext);
    }

    public virtual IOwinContext GetOwinContext()
    {
        return HttpContext.Current.GetOwinContext();
    }
}

Then your UT will be:

[Test]
public void New_GUID_should_be_added_when_OnActionExecuting_is_executing()
{
    //arrange section:
    const string REQUEST_GUID_FIELD_NAME = "RequestGUID";
    var owinContext = MockRepository.GenerateStub<IOwinContext>();

    var target = MockRepository.GeneratePartialMock<MyCustonAttributte>();

    target.Stub(x => x.GetOwinContext())
        .Return(owinContext);

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

    //assert section:
    owinContext.AssertWasCalled(x => x.Set(Arg<string>.Is.Equal(REQUEST_GUID_FIELD_NAME),
        Arg<Guid>.Is.NotEqual(Guid.Empty)));
}
like image 185
Old Fox Avatar answered Nov 03 '22 12:11

Old Fox