2010-02-11 118 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的其餘部分,因爲我不確定這些行的目的究竟是什麼。