使用RouteAttribute对ApiControllers进行单元测试

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

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

16

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接