模拟 Asp.net-mvc 控制器上下文 [英] Mocking Asp.net-mvc Controller Context
问题描述
因此控制器上下文取决于一些 asp.net 内部结构.有哪些方法可以为单元测试干净地模拟这些?当我只需要例如 Request.HttpMethod 返回GET"时,似乎很容易用大量设置阻塞测试.
So the controller context depends on some asp.net internals. What are some ways to cleanly mock these up for unit tests? Seems like its very easy to clog up tests with tons of setup when I only need, for example, Request.HttpMethod to return "GET".
我在网上看到了一些例子/帮助者,但有些已经过时了.认为这是一个保存最新和最好的好地方.
I've seen some examples/helpers out on the nets, but some are dated. Figured this would be a good place to keep the latest and greatest.
我正在使用最新版本的犀牛模拟
I'm using latest version of rhino mocks
推荐答案
使用 MoQ 看起来像这样:
Using MoQ it looks something like this:
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 的语法是相似的.
I think the Rhino Mocks syntax is similar.
这篇关于模拟 Asp.net-mvc 控制器上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!