0

我有一个代码段:

var requestMock = new Mock<HttpRequestBase>();
var queryString = new NameValueCollection();
queryString["abc"] = "123";
queryString["qwe"] = "456";
queryString["yui"] = "678";
...
requestMock.SetupGet(rqst => rqst.QueryString).Returns(queryString);

现在,我想将上面的段写成一个方法:

var requestMock = GetRequestMock(???);

我打算发送可以是任何内容的查询字符串键/值。k/v 对的数量也可以是任何值。

public Mock<HttpRequestBase> GetRequestMock(???)
{
var requestMock = new Mock<HttpRequestBase>();
....
requestMock.SetupGet(rqst => rqst.QueryString).Returns(queryString);
return requestMock;
}

有效和简单地做到这一点的最佳方法是什么?

4

1 回答 1

2

一种方法是使用Dictionary

public Mock<HttpRequestBase> GetRequestMock(Dictionary<string, object> queryParms)
{
    var queryString = new NameValueCollection();
    foreach (KeyValuePair<string, object> kvp in queryParms)
    {
        queryString[kvp.Key] = Convert.ToString(kvp.Value);
    }

    ...
}

然后你可以这样称呼它:

GetRequestMock(new Dictionary<string, object> { { "abc", "123" }, { "qwe", "456" } } );
于 2013-04-10T17:38:29.107 回答