gpt4 book ai didi

c# - 如何使用 NUnit 和 Rhino Mocks 模拟 HttpContext.Current.Items

转载 作者:太空宇宙 更新时间:2023-11-03 21:01:17 24 4
gpt4 key购买 nike

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

我正在尝试为一种方法编写测试,它应该向 HttpContext.Current.Items 添加一个项目。

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

我不知道如何让 HttpContext.Current.Items 从测试方法中运行时可用于该方法。我怎样才能做到这一点?

此外,我如何检查该项目是否已添加(我可以/应该使用什么样的断言)

最佳答案

您根本不需要重构代码\使用 RhinoMocks 来测试它。

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

[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:

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

关于c# - 如何使用 NUnit 和 Rhino Mocks 模拟 HttpContext.Current.Items,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45239728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com