views:

252

answers:

1

Hello, I'm using the Moq framework to do my unit testing. I'm following some really useful instructions outlined here to help me mock the httpcontext, specifically for the purposes of testing the url referrer:

http://my6solutions.com/post/2009/08/18/Mocking-HttpContext-in-ASP-NET-MVC.aspx

Everything seems to compile fine, however when running the test I get the following error:

System.Web.HttpException: Invalid use of SimpleWorkerRequest constructor. Application path cannot be overridden in this context. Please use SimpleWorkerRequest constructor that does not override the application path..

When analyzing I find the error seems to be thrown at the following line:

var wr = new SimpleWorkerRequest("", "", "", "", writer);

I'm not sure what to make of this. What is the SimpleWorkerRequest and how does it work in creating the HttpContext in Moq?? Why is my use of it invalid according to the debugger??

UPDATE: Here is the complete method I use taken from the website above

public static HttpContextBase FakeHttpContext()
        {
            var httpContext = new Mock<HttpContextBase>();
            var request = new Mock<HttpRequestBase>();
            var response = new Mock<HttpResponseBase>();
            var session = new Mock<HttpSessionStateBase>();
            var server = new Mock<HttpServerUtilityBase>();
            var cookies = new HttpCookieCollection();

            httpContext.Setup(x => x.Server).Returns(server.Object);
            httpContext.Setup(x => x.Session).Returns(session.Object);
            httpContext.Setup(x => x.Request).Returns(request.Object);
            httpContext.Setup(x => x.Response).Returns(response.Object);

            response.Setup(x => x.Cookies).Returns(cookies);
            httpContext.SetupGet(x => x.Request.Url).Returns(new Uri("http://www.csuci.edu"));
            httpContext.SetupGet(x => x.Request.UrlReferrer).Returns(new Uri("http://www.csuci.edu"));
            //var writer = new StringWriter();
            //var wr = new SimpleWorkerRequest("", "", "", "", writer);
            //HttpContext.Current = new HttpContext(wr);
            return httpContext.Object;
        }

I commented out the problem lines, that seemed to fix it, but I'm still not sure what those lines were supposed to do and why they were causing error.

A: 

See UPDATE section above, if you follow the example provided in the link above and remove the specific lines commented out above, that seems to fix the problem if all you're looking for is to fake the UrlReferrer, which is what I was after. Not sure how that would affect the rest of the fake httpContext, as I'm not sure exactly what the purpose of those lines was.

kingrichard2005