使用路由属性对Api控制器进行单元测试

时间:2014-01-28 17:09:10

标签: c# unit-testing asp.net-mvc-routing asp.net-web-api2

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

最接近解决方案的是首先使用属性进行路由的方法: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);
    }
}

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

1 个答案:

答案 0 :(得分: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