模拟Asp.net-mvc控制器上下文

因此,控制器上下文取决于一些asp.net内部。有什么方法可以完全模拟这些以进行单元测试?当我仅需要例如Request.HttpMethod返回“ GET”时,似乎很容易用大量设置阻塞测试。

我已经在网上看到了一些例子/帮助者,但其中有些是过时的。认为这将是保持最新和最佳状态的好地方。

我正在使用最新版本的犀牛模拟


尚方宝剑之说
浏览 621回答 3
3回答

汪汪一只猫

使用最小起订量看起来像这样:var request = new Mock<HttpRequestBase>();request.Expect(r => r.HttpMethod).Returns("GET");var mockHttpContext = new Mock<HttpContextBase>();mockHttpContext.Expect(c => c.Request).Returns(request.Object);var controllerContext = new ControllerContext(mockHttpContext.Object, new RouteData(), new Mock<ControllerBase>().Object);我认为Rhino Mocks的语法相似。

慕侠2389804

这是Jason链接的摘录。与Phil的方法相同,但使用犀牛。注意:在嘲笑了mockRequest的内部之前,将嘲笑mockHttpContext.Request 返回mockRequest 。我相信此命令是必需的。// create a fake web contextvar mockHttpContext = MockRepository.GenerateMock<HttpContextBase>();var mockRequest = MockRepository.GenerateMock<HttpRequestBase>();mockHttpContext.Stub(x => x.Request).Return(mockRequest);// tell the mock to return "GET" when HttpMethod is calledmockRequest.Stub(x => x.HttpMethod).Return("GET");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;var controller = new AccountController();// assign the fake contextvar context = new ControllerContext(mockHttpContext,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new RouteData(),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; controller);controller.ControllerContext = context;// act...
打开App,查看更多内容
随时随地看视频慕课网APP