2010-02-11 116 views
0

我正在使用Moq框架来做我的单元测试。运行测试我得到的时候ASP.Net MVC单元测试异常

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

一切似乎编译正常,但是:我下面这里列出来帮我嘲笑的HttpContext一些真正有用的指示,专门用于测试的URL引用的目的以下错误:

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..

在分析我发现错误似乎在下面的行抛出:

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

我不知道该怎么做。什么是SimpleWorkerRequest以及它如何在Moq中创建HttpContext?为什么根据调试器使用它无效?

更新:下面是完整的方法,我使用的网站采取上述

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; 
     } 

我注释掉问题的线条,似乎修复它,但我仍然不知道这些行被认为要做什么以及为什么他们造成错误。

+0

您可能需要公开更多的代码才能了解为什么它不喜欢您正在做的事情......您可以在有问题的行之前提供更多的代码吗? – curtisk 2010-02-11 19:13:55

回答

0

查看上面的更新部分,如果你按照上面的链接提供的例子,并删除上面注释的特定行,这似乎解决了问题,如果你只是想伪造UrlReferrer,这是什么我在之后。不知道这将如何影响假httpContext的其余部分,因为我不确定这些行的目的究竟是什么。