使用RouteAttribute对ApiControllers进行单元测试

 xhl583337984 发布于 2023-01-30 18:41

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

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

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

1 个回答
  • 这太荒谬了......我用它来工作:

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

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

    但现在它有效,我很高兴.

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

    2023-01-30 18:42 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有