使用下面的单元测试..我正在尝试测试我的 webapi。
[Test]
public void CheckControllerForCreate()
{
var config = new HttpConfiguration();
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/product");
var route = config.Routes.MapHttpRoute("Foo", "api/{controller}/{id}");
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "products" } });
var controller = new ProductController
{
ControllerContext = new HttpControllerContext(config, routeData, request),
Request = request,
Url = new UrlHelper(request)
};
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
var result = controller.Create(new Product {Id = 4, Name = "Tomato Soup", Category = "Groceries", Price = 1});
}
[HttpPost]
public HttpResponseMessage Create(Product product)
{
var url = Url;
if (product == null)
throw new HttpResponseException(new HttpResponseMessage{StatusCode = HttpStatusCode.BadRequest,ReasonPhrase = "Product is not specified"});
products.Add(product);
var response = Request.CreateResponse(HttpStatusCode.Created, product);
string uri = Url.Link("Foo", product.Id);
response.Headers.Location = new Uri(uri);
return response;
}
Create Action 引发异常,因为uri
is null
。现在,Url 助手正在正确获取 RouteName ,否则将出现 RouteName not found 异常。我假设我的配置有问题。
我参考了http://www.peterprovost.org/blog/2012/06/16/unit-testing-asp-dot-net-web-api和其他几篇文章来对控制器进行单元测试。
WebAPI 方法在 codeplex 上
编辑
我已将其范围缩小到 vpd 在(UrlHelper)中为空
IHttpVirtualPathData vpd = configuration.Routes.GetVirtualPath(
request: request,
name: routeName,
values: routeValues);
似乎无法弄清楚为什么?