我认为在网上进行简单搜索的结果不止于此.
最接近解决方案的是首先使用属性进行路由的方法:AttributeRouting不使用HttpConfiguration对象来编写集成测试
但是ASP.NET Web Api 2呢?
HttpConfiguration config = new HttpConfiguration(); // config.MapHttpAttributeRoutes(); // This doesn't work. I guess there is needed some more plumbing to know what Controllers to search for attributes, but I'm lost here. HttpServer server = new HttpServer(config); using (HttpMessageInvoker client = new HttpMessageInvoker(server)) { using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, "http://localhost/api/accounts/10")) using(HttpResponseMessage response = client.SendAsync(request, CancellationToken.None).Result) { response.StatusCode.Should().Be(HttpStatusCode.Created); } }
如何注入我的控制器,以便它读取Controller上的属性并设置路由,以便我可以实际进行一些测试?
这太荒谬了......我用它来工作:
config.MapHttpAttributeRoutes(); config.EnsureInitialized();
所以基本上,这会运行配置的初始化config.MapHttpAttributeRoutes()
.我想,我原以为这是自动完成的.
但现在它有效,我很高兴.
有关此问题的详细信息,请参阅:http://ifyoudo.net/post/2014/01/28/How-to-unit-test-ASPNET-Web-API-2-Route-Attributes.aspx