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

大城市里の小女人 提交于 2020-01-04 04:06:34

问题


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?


回答1:


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)));
}


来源:https://stackoverflow.com/questions/45305608/how-to-mock-httpcontext-current-getowincontext-with-nunit-and-rhinomocks

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