How can I make fun of the value of ASP.NET ServerVariables ["HTTP_HOST"]?

I have the following code that does not work at runtime ...

var mock = new Mock<ControllerContext>();
mock.SetupGet(x => x.HttpContext.Request
    .ServerVariables["HTTP_HOST"]).Returns(domain);

** RunTime Error: Incorrect setting for uncaught Property

I have code in my controller that should check the domain to which the user requested / left.

I'm not sure how to taunt this? any ideas?

PS. I am using mq framewoke in the above example. So I'm not sure if this is a problem, etc.?

+5
source share
2 answers

NameValueCollection, . , , - mock ServerVariables, . NameValueCollection. .

:

 var context = new Mock<ControllerContext>();
 NameValueCollection variables = new NameValueCollection();
 variables.Add("HTTP_HOST", "www.google.com"); 
 context.Setup(c => c.HttpContext.Request.ServerVariables).Returns(variables);
 //This next line is just an example of executing the method 
 var domain = context.Object.HttpContext.Request.ServerVariables["HTTP_HOST"];
 Assert.AreEqual("www.google.com", domain);
+6

HttpContext :

interface IHttpContextValues
{
    string HttpHost { get; }
}

class HttpContextValues : IHttpContextValues
{
    public string HttpHost
    {
        get { return HttpContext.Current.Request.ServerVariables["HTTP_HOST"]; }
    }
}

class BaseController : Controller
{
    public IHttpContextValues HttpContextValues;
    BaseController()
    {
        HttpContextValues = new HttpContextValues();
    }
}

HttpContextValues ​​ ControllerContext.HttpContext . - .

+1

All Articles