How do you test your Request.QueryString[] variables?

前端 未结 11 2173
梦如初夏
梦如初夏 2020-11-29 16:05

I frequently make use of Request.QueryString[] variables.

In my Page_load I often do things like:

       int id = -1;

             


        
11条回答
  •  半阙折子戏
    2020-11-29 16:29

    Eeee this is a karma risk...

    I have a DRY unit-testable abstraction because, well, because there were too many querystring variables to keep on in a legacy conversion.

    The code below is from a utility class whose constructor requires a NameValueCollection input (this.source) and the string array "keys" is because the legacy app was rather organic and had developed the possibility for several different strings to be a potential input key. However I kind of like the extensibility. This method inspects the collection for the key and returns it in the datatype required.

    private T GetValue(string[] keys)
    {
        return GetValue(keys, default(T));
    }
    
    private T GetValue(string[] keys, T vDefault)
    {
        T x = vDefault;
    
        string v = null;
    
        for (int i = 0; i < keys.Length && String.IsNullOrEmpty(v); i++)
        {
            v = this.source[keys[i]];
        }
    
        if (!String.IsNullOrEmpty(v))
        {
            try
            {
                x = (typeof(T).IsSubclassOf(typeof(Enum))) ? (T)Enum.Parse(typeof(T), v) : (T)Convert.ChangeType(v, typeof(T));
            }
            catch(Exception e)
            {
                //do whatever you want here
            }
        }
    
        return x;
    }
    

提交回复
热议问题