使用RouteatTribute进行单位测试



我认为网络上的一个简单搜索比这更重要。

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

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

这只是荒谬的...我使用此操作了:

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

基本上,这运行了config.MapHttpAttributeRoutes()的配置的初始化。我想,我会认为这是自动完成的。

但是现在它有效,我很高兴。

有关此问题的更多信息,请参见:http://ifyoudo.net/post/2014/01/01/28/how-to-to-unit-test-test-aspnet-web-api-2-route-attributes.aspx

最新更新