One of my services uses the server variable provided by IIS with this code
var value = System.Web.HttpContext.Current.Request.ServerVariables["MY_CUSTOM_VAR"];
What I tried is to mock this object and insert my own variable / collection and check for several cases (for example, there is no variable, the value is null ...) I can create instances of HttpContext, HttpRequest, HttpResponse and assign them properly, but each one is a simple class with no interface or virtual properties, and ServerVariables initialization takes place somewhere under the hood.
HttpContext mocking:
var httpRequest = new HttpRequest("", "http://excaple.com/", ""); var stringWriter = new StringWriter(); var httpResponse = new HttpResponse(stringWriter); var httpContextMock = new HttpContext(httpRequest, httpResponse); HttpContext.Current = httpContextMock;
Attempt # 1 to call a private method using reflection
var serverVariables = HttpContext.Current.Request.ServerVariables; var serverVariablesType = serverVariables.GetType(); MethodInfo addStaticMethod = serverVariablesType.GetMethod("AddStatic", BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic); addStaticMethod.Invoke(serverVariables, new object[] {"MY_CUSTOM_VAR", "value"});
Failed to say the assembly is read-only.
Attempt # 2 Replace server variables with my own instance
var request = HttpContext.Current.Request; var requestType = request.GetType(); var variables = requestType.GetField("_serverVariables", BindingFlags.Instance | BindingFlags.NonPublic); variables.SetValue(request, new NameValueCollection { { "MY_CUSTOM_VAR", "value" } });
Error with the error that it is impossible to pour NameValueCollection in the HttpServerVarsCollection. This is because the HttpServerVarsCollection is actually an inner class, so I could not either instantiate or apply it.
So the question is, how can I mock ServerVariables or insert a value there? Thanks