模拟HttpContext以检索项目表单上下文项目字典

k.c*_*.c. 0 rhino-mocks http asp.net-mvc-3

我们使用MVC3,对于我们的单元测试,我们在单元测试中使用RhinoMocks.当请求开始时,我们检查它来自的域并将其与客户匹配.该客户存储在HttpContext.Items中.大多数控制器需要这些信息来完成他们的工作

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()
                    ) 
        };
       ...
Run Code Online (Sandbox Code Playgroud)

此代码示例基本上显示了所需的内容,但不允许存根,因为HttpContext是一个"密封"类.控制器接受一个HttpContextBase(有很多关于模拟这个),但它不公开Items属性.

想什么?甚至更好的解决方案;-)

Jer*_*oen 5

创建HttpContextBase存根并对其Items属性进行存根将允许您使用Items字典:

        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;
Run Code Online (Sandbox Code Playgroud)