Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Auto-mock setup for Web API
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Hosting;
using System.Web.Http.Routing;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using NSubstitute;
public class AutoMockWebApiAttribute : AutoMockAspectAttribute
{
public static readonly string CurrentController = "_CurrentController_";
private HttpConfiguration config;
private HttpRequestMessage request;
public override void Bind(IAutoMock autoMock)
{
var routeData = Substitute.For<IHttpRouteData>();
var routeValues = new Dictionary<string, object> { { "controller", CurrentController } };
routeData.Values.Returns(routeValues);
routeData.Route.Returns(Substitute.For<IHttpRoute>());
autoMock.Kernel.Bind<IHttpRouteData>().ToConstant(routeData);
config = new HttpConfiguration();
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
autoMock.Kernel.Bind<HttpConfiguration>().ToConstant(config);
autoMock.Kernel.Bind<HttpRouteCollection>().ToConstant(config.Routes);
request = new HttpRequestMessage(HttpMethod.Get, new Uri("http://localhost:1337/request"));
request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
autoMock.Kernel.Bind<HttpRequestMessage>().ToConstant(request);
var controllerContext = new HttpControllerContext(config, routeData, request);
autoMock.Kernel.Bind<HttpControllerContext>().ToConstant(controllerContext);
var controllerDescriptor = Substitute.For<HttpControllerDescriptor>(config, CurrentController, typeof(DummyController));
autoMock.Kernel.Bind<HttpControllerDescriptor>().ToConstant(controllerDescriptor);
var actionDescriptor = Substitute.For<HttpActionDescriptor>(controllerDescriptor);
autoMock.Kernel.Bind<HttpActionDescriptor>().ToConstant(actionDescriptor);
var actionContext = new HttpActionContext(controllerContext, actionDescriptor);
autoMock.Kernel.Bind<HttpActionContext>().ToConstant(actionContext);
}
public override void OnObjectCreated(IAutoMock autoMock, object obj)
{
var controller = obj as ApiController;
if (controller != null)
controller.Request = request;
}
class DummyController : ApiController { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment