如何存根HttpControllerContext [英] how to stub HttpControllerContext

查看:415
本文介绍了如何存根HttpControllerContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图单元测试一块code那被从的WebAPI(的OData)控制器调用,并需要在HttpControllerContext:

I am trying to unit-test a piece of code that gets called from a WebAPI (OData) controller and takes in an HttpControllerContext:

public string MethodToTest(HttpControllerContext context)
{
    string pub = string.Empty;

    if (context != null)
    {
        pub = context.Request.RequestUri.Segments[2].TrimEnd('/');
    }

    return pub;
}

要进行单元测试这一点,我需要一个HttpControllerContext对象。我应该怎么做呢?我最初是想用微软正版正货存根,但HttpControllerContext不似乎有一个接口(为什么?),因此多数民众赞成似乎没有成为一种选择。如果我只是新的一个新的HttpControllerContext对象,也许存根其构造函数的参数?或使用该起订量架构(而不是!)

To Unit-test this i need an HttpControllerContext object. How should i go about it? I was initially trying to stub it with Microsoft Fakes, but HttpControllerContext doesnt seem to have an interface (why??), so thats doesnt seem to be an option. Should i just new up a new HttpControllerContext object and maybe stub its constructor parameters? Or use the Moq framework for this (rather not!)

推荐答案

您可以简单地实例化一个 HttpControllerContext 并指定上下文对象给它,除了路由信息(您可以模拟所有这些):

You can simply instantiate an HttpControllerContext and assign context objects to it, in addition to route information (you could mock all of these):

var controller = new TestController();
var config = new HttpConfiguration();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/test");
var route = config.Routes.MapHttpRoute(null, "api/{controller}/{id}");
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "test" } });

controller.ControllerContext = new HttpControllerContext(config, routeData, request);
controller.Request = request;
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;

// Call your method to test
MethodToTest(controller);

HttpControllerContext 只是一个容器,这样就不必被嘲笑自己。

HttpControllerContext is simply a container so it does not have to be mocked itself.

这篇关于如何存根HttpControllerContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆