简体   繁体   中英

Unit test Request.QueryString.ToString()

I want to unit test a method that uses Request.QueryString , used like this:

 public void GetUrl(string url)
    {
        var queryString = this.context.Request.QueryString.ToString();

        var urlWithQueryString = url;
        if (!string.IsNullOrEmpty(queryString))
        {
            urlWithQueryString = url + (url.Contains("?") ? "&" : "?") + queryString;
        }

        return urlWithQueryString;
    }

I try to stub the QueryString like this using Moq, with no suceess:

Mock<HttpRequestBase> Request = new Mock<HttpRequestBase>();
Request.SetupGet(r => r.QueryString).Returns(new NameValueCollection());

Because the production code return name/value pairs, or empty string, while the unit test returns the full name of the class NameValueCollection .

Any idea?

The reason why that happens is that at runtime, Request.QueryString is not exactly a NameValueCollection , but a HttpValueCollection - a derivative of NameValueCollection that overrides ToString to give you that nicely formatted result.

The HttpValueCollection class is private, so you cannot directly create an instance of it, but you can do this indirectly, as described in this answer .

Concretely, instead of new NameValueCollection() you should use HttpUtility.ParseQueryString("") .

The resulting object implements the standard NameValueCollection , so you can for example call Add(string name, string value) after instantiating it.

Alternatively, you can pass a real querystring when creating it: HttpUtility.ParseQueryString("a=1&b=2")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM