Access Mocked Request.ServerVariables in classes

1.4k Views Asked by At

I have mocked Server Variables which are used in Controller.

request.SetupGet(x => x.ServerVariables)
    .Returns(new System.Collections.Specialized.NameValueCollection
    {
        {"SERVER_NAME","localhost"}, 
        {"SCRIPT_NAME","localhost"}, 
        {"SERVER_PORT","80"}, 
        {"HTTPS","www.melaos.com"}, 
        {"REMOTE_ADDR","127.0.0.1"}, 
        {"REMOTE_HOST","127.0.0.1"} 
    });

I can get the values of Server variables in Controller but not in Model classes. Why is it so?

The only difference in getting the value in Controller and Model is that in Controller we write HttpContext.Request.ServerVariables while in Model we write HttpContext.Current.Request.ServerVariables.

Are they different? How can I get these values in Model as well.

1

There are 1 best solutions below

0
On

while in Model we write HttpContext.Current.Request.ServerVariables.

HttpContext.Current is the problem. It's a static property that you cannot mock and that cannot be used outside of an ASP.NET context such as a unit test. So if you use HttpContext.Current you cannot unit test your application. This being said you should not use any HTTP specific artifacts in your model. You should directly pass the values from your controller to the model so that the model doesn't try to fetch them.