how to stub HttpControllerContext

耗尽温柔 提交于 2019-11-29 02:54:28

问题


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

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


回答1:


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("default", "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 is simply a container so it does not have to be mocked itself.



来源:https://stackoverflow.com/questions/21261992/how-to-stub-httpcontrollercontext

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