嘲讽的HttpContext检索项表单上下文项词典 [英] Mocking HttpContext to retrieve item form contexts item dictionary
问题描述
我们使用MVC3,为我们在单元测试中使用RhinoMocks的单元测试。
当一个请求开始我们检查从它来和匹配给客户的域。
该客户存储于HttpContext.Items。
大多数控制器需要这个信息,以做好自己的事情。
We use MVC3, for our unit tests we use RhinoMocks in our unit tests. When the a request starts we check the domain from which it came and match that to a customer. This customer is stored in the HttpContext.Items. Most controllers need this info to do their thing.
var mocks = new MockRepository();
using (var controller = new TestController())
{
HttpContext context =
MockRepository.GenerateStub<HttpContext>();
Customer customer = new Customer { Key = "testKey" };
context.Items["Customer"] = customer;
controller.ControllerContext =
new ControllerContext {
Controller = controller,
RequestContext =
new RequestContext(
new HttpContextWrapper(context),
new RouteData()
)
};
...
这code样本显示基本上需要什么,但是存根不允许作为HttpContext的是密封类。
该控制器接受HttpContextBase(有很多关于嘲笑这一个),但它不公开的项目属性。
This code sample shows basically what is needed, however the stub is not allowed as HttpContext is a "sealed" class. The controller accepts a HttpContextBase (there is lot about mocking this one), but it does not expose the Items property.
思考的人?甚至更好的解决方案; - )
Thoughts anyone? Or even better a solution ;-)
推荐答案
创建 HttpContextBase
存根和存根其项目
属性将允许您使用项目
词典:
Creating a HttpContextBase
stub and stubbing its Items
property will allow you to use the Items
dictionary:
HttpContextBase context =
MockRepository.GenerateStub<HttpContextBase>();
Customer customer = new Customer { Key = "testKey" };
context.Stub(c => c.Items).Return(new Dictionary<string, object>());
context.Items["Customer"] = customer;
这篇关于嘲讽的HttpContext检索项表单上下文项词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!