Web API 1 で正しく動作していた統合テストはほとんどありません。Web API 2 (5.0) にアップグレードした後、それらは動作せず、次のコードを呼び出すと null 参照が返されます。
string uri = Url.Link(HttpRouteConstants.RouteName, new { param1 =
paramValue1, param2 = paramValue2 });
基本的にUrl.Linkはルートを見つけることができません (少なくともこれが問題だと思います)。問題は、HttpConfigurationとルートが Web API 2 に登録される方法にあると思います。WebApiConfig登録呼び出しを変更する必要がありました。
から
WebApiConfig.Register(config)
に
GlobalConfiguration.Configure(WebApiConfig.Register);
そして今、 HttpServerにHttpConfigurationインスタンスを提供している統合テストセットアップを使用すると、GlobalConfiguration.Configure(WebApiConfig.Register);のようなものを呼び出すことができません。しかし、私は古い方法を使用しており、正しく機能していないように見える次のWebApiConfig.Register(config)を実行しています。参考までに、私のルーティング構成は WebApiConfig に配置されています。
誰かが回避策を知っていますか?
これは私が使用しているスタックです:
- VS 2013 (.NET 4.5.1)
- WebAPI 2 (慣例に基づくルーティングと属性ルーティング)
- xUnit
- ニンジェクト
アップデート
統合テストのコード サンプルは次のとおりです。
// Create configuration
HttpConfiguration config = new HttpConfiguration();
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
config.DependencyResolver = new NinjectDependencyResolver(Kernel);
//WebApiConfig.Register(config); Below is the excerpt from WebApiConfig
config.EnableCors((System.Web.Http.Cors.ICorsPolicyProvider)config.DependencyResolver.GetService(typeof(System.Web.Http.Cors.ICorsPolicyProvider)));
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: HttpRouteConstants.ApplicationAPIRouteName,
routeTemplate: CoreRouteConstants.DefaultApplicationControllerRoute + "/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: HttpRouteConstants.DefaultAPIRouteName,
routeTemplate: CoreRouteConstants.DefaultControllerRoute + "/{id}",
defaults: new { id = RouteParameter.Optional }
);
HttpServer server = null;
try
{
server = new HttpServer(config);
}
catch (Exception ex)
{
throw ex;
}
string controller = String.Format("{0}{1}/api/MyController/{2}/", HttpServerBaseAddress, param1, param2);
var client = new HttpClient(Server);
using (HttpResponseMessage response = client.DeleteAsync(controller, new CancellationTokenSource().Token).Result)
{
response.IsSuccessStatusCode.Should().BeFalse();
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
//Below is the code from MyController
public virtual async Task<HttpResponseMessage> DeleteAsync([FromUri]object key)
{
HttpResponseMessage response = null;
HttpStatusCode statusCode = HttpStatusCode.OK;
bool result = await Store.DeleteAsync(key);
if (!result)
statusCode = HttpStatusCode.NotFound;
response = Request.CreateResponse<bool>(statusCode, result);
string uri = Url.Link(HttpRouteConstants.ApplicationAPIRouteName, new { param1 = "param1", id = key });
//NOTE: uri is null here as I mentioned
response.Headers.Location = new Uri(uri);
return response;
}
ありがとう