我认为在网络上进行简单的搜索结果不仅仅是这样。
最接近解决方案的是第一次允许使用属性进行路由:AttributeRouting not working with HttpConfiguration object for writing Integration tests。
但是ASP.NET Web 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);
}
}我如何注入我的控制器,以便它读取控制器上的属性并设置路由,这样我就可以实际地进行一些测试了?
发布于 2014-01-28 22:18:56
这太荒谬了..。我用这个让它发挥作用:
config.MapHttpAttributeRoutes();
config.EnsureInitialized();因此,基本上,这将运行config.MapHttpAttributeRoutes()配置的init。我想,我会以为这是自动完成的。
但现在起作用了我很高兴。
有关此问题的更多信息,请参见:http://ifyoudo.net/post/2014/01/28/How-to-unit-test-ASPNET-Web-API-2-Route-Attributes.aspx
https://stackoverflow.com/questions/21412161
复制相似问题