【问题标题】:How can I Mock HttpRequest[] indexer property如何模拟 HttpRequest[] 索引器属性
【发布时间】:2012-05-15 23:56:42
【问题描述】:

我正在向用 C#/ASP.NET/webforms 编写的大型遗留代码库添加单元测试。我们正在使用 MOQ 和 XUnit。我们已经能够使用如下语法模拟查询字符串值:

Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();
NameValueCollection queryStringParams = new NameValueCollection();
queryStringParams.Add("name", "Fred Jones");
request.Setup(x => x.QueryString).Returns(queryStringParams);

这让这段代码可以正常工作:

string name = _mockRequest.QueryString["name"];

问题在于,在整个代码库中散布着许多用于获取查询字符串变量或表单变量的调用:

string name = HttpContext.Current.Request["name"];

索引器显然会查看所有不同的集合:查询字符串、表单值、cookie 和服务器变量。我不想通过重构生产代码以使用其中一个集合来引入很多潜在的副作用。

有人知道在 HttpRequest 上模拟该索引器的方法吗?

【问题讨论】:

  • WebForms 还是 MVC?使用 MVC,您可以设置 controller.ControllerContext
  • 看看 mvc-contrib 测试助手。它为您开箱即用。
  • 此链接可能会有所帮助:stackoverflow.com/a/1214233/220061
  • 是的,我们正在按照该帖子的建议模拟上下文和请求。正是这个特定的索引器给我们带来了问题。

标签: c# moq httprequest xunit


【解决方案1】:

我想出了这个,它比我做的要简单。

//
// Set a variable in the indexer collction
//
Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();
request.SetupGet(r => r["name"]).Returns("Fred Jones");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-16
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多