Mocking HttpContext to retrieve item form contexts item dictionary

时光毁灭记忆、已成空白 提交于 2019-12-12 03:59:54

问题


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()
                    ) 
        };
       ...

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 ;-)


回答1:


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;


来源:https://stackoverflow.com/questions/7594510/mocking-httpcontext-to-retrieve-item-form-contexts-item-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!