如何在单元测试c#controller中传递session和Request.URL

时间:2017-01-20 22:34:52

标签: c# asp.net-mvc visual-studio unit-testing

我有一个控制器,它需要会话状态对象和Url Helper都要从单元测试中进行模拟,在这方面我创建了以下代码

   [TestMethod]
         public void PaymentControllerTest_CallPaymentProvider()
         {

             var controller = new PaymentController();
             //  var model = new Dictionary<string, string>();
             var mockDatabaseWrapper = new MockDatabaseWrapper();
             DatabaseWrapper.SetDatabaseWrapper(mockDatabaseWrapper);


             var request = new Mock<HttpRequestBase>();
             request.SetupGet(x => x.Headers).Returns(
              new System.Net.WebHeaderCollection {
             {"X-Requested-With", "XMLHttpRequest"} });

             request.SetupGet(x => x.Url).Returns(new Uri("http://localhost"));
             var context = new Mock<HttpContextBase>();
             context.SetupGet(x => x.Request).Returns(request.Object);


             controller.ControllerContext = new ControllerContext(context.Object, new System.Web.Routing.RouteData(), controller);

             controller.Url = new UrlHelper(new System.Web.Routing.RequestContext(controller.HttpContext, new RouteData()), new RouteCollection());
             RouteCollection routes = new System.Web.Routing.RouteCollection();



             var mockControllerContext = new Mock<ControllerContext>();
             var mockSession = new Mock<HttpSessionStateBase>();
             mockSession.SetupGet(Session => Session["CurrentCulture"]).Returns(1); //somevalue
             mockControllerContext.Setup(p => p.HttpContext.Session).Returns(mockSession.Object);

             var result = controller.CallPaymentProvider(123) as ViewResult; 
         }

现在的问题是,当我创建控制器上下文时,我只能传递一个。任何专家都可以帮助如何在控制器上下文中传递会话和URL。

由于

0 个答案:

没有答案