Skip to content

Instantly share code, notes, and snippets.

@raghuramn
Created August 23, 2013 17:48
Show Gist options
  • Save raghuramn/6322041 to your computer and use it in GitHub Desktop.
Save raghuramn/6322041 to your computer and use it in GitHub Desktop.
route testing
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using Xunit;
using Xunit.Extensions;
namespace TestRoutes
{
public class TestRoutes
{
[Theory]
[InlineData("http://localhost/Customers/42", "Test", "GetCustomer")]
[InlineData("http://localhost/Customers", "Test", "GetCustomers")]
[InlineData("http://localhost/Customers/42/Name", "Test", "GetCustomerName")]
public void RegisteredRoutes_MatchRight_ControllerAndAction(string uri, string expectedController, string expectedAction)
{
// Arrange
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Services.Replace(typeof(IHttpActionInvoker), new TestActionInvoker());
HttpServer server = new HttpServer(config);
HttpClient client = new HttpClient(server);
// Act
var response = client.GetAsync(uri).Result;
// Assert
response.EnsureSuccessStatusCode();
Tuple<string, string> result = response.Content.ReadAsAsync<Tuple<string, string>>().Result;
Assert.Equal(expectedController, result.Item2);
Assert.Equal(expectedAction, result.Item1);
}
}
// Return the action/controller metadata as response instead of invoking the actual action.
public class TestActionInvoker : IHttpActionInvoker
{
public Task<HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
var response = actionContext.Request.CreateResponse(HttpStatusCode.OK,
Tuple.Create(
actionContext.ActionDescriptor.ActionName,
actionContext.ControllerContext.ControllerDescriptor.ControllerName));
return Task.FromResult(response);
}
}
public class TestController : ApiController
{
[Route("Customers")]
public void GetCustomers()
{
}
[Route("Customers/{id:int}")]
public void GetCustomer(int id)
{
}
[Route("Customers/{id:int}/Name")]
public void GetCustomerName(int id)
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment