10

我以为是在网络上进行的简单搜索结果却不止于此。

最接近解决方案的是第一个可以使用属性进行路由的解决方案:AttributeRouting not working with HttpConfiguration object for writing Integration tests

但是 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);
    }
}

如何注入我的控制器,以便它读取控制器上的属性并设置路由,以便我可以实际进行一些测试?

4

1 回答 1

16

这太荒谬了......我使用它来工作:

config.MapHttpAttributeRoutes();
config.EnsureInitialized();

所以基本上,这会运行config.MapHttpAttributeRoutes(). 我想,我会认为这是自动完成的。

但现在它起作用了,我很高兴。

有关此问题的更多信息,请参阅:http: //ifyoudo.net/post/2014/01/28/How-to-unit-test-ASPNET-Web-API-2-Route-Attributes.aspx

于 2014-01-28T22:18:56.010 回答