如何使用NUnit和Rhino Mocks模拟HttpContext.Current.Items [英] How to mock HttpContext.Current.Items with NUnit and Rhino Mocks

查看:75
本文介绍了如何使用NUnit和Rhino Mocks模拟HttpContext.Current.Items的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NUnitRhinoMocks在(WebApi)项目上进行单元测试.

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

有一种我正在尝试为其编写测试的方法,该方法应该将一个项目添加到HttpContext.Current.Items.

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

我不知道从测试方法中运行时如何使HttpContext.Current.Items可用于该方法.我该如何实现?

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)

推荐答案

您不需要重构代码\完全使用RhinoMocks进行测试.

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

您的UT应该类似于以下示例:

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

顺便说一句,您可以将此测试分为2个:

BTW, you can split this test to 2:

  1. 验证是否已使用GUID填充RequestGUID
  2. 验证GUID不是Guid.Empty

这篇关于如何使用NUnit和Rhino Mocks模拟HttpContext.Current.Items的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆