c# - 使用 RouteAttribute 对 ApiController 进行单元测试

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

我如何注入(inject)我的 Controller ,以便它读取 Controller 上的属性并设置路由,这样我才能真正进行一些测试?

最佳答案

这太荒谬了......我用这个让它工作:

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

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

但现在可以用了,我很高兴。

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

关于c# - 使用 RouteAttribute 对 ApiController 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21412161/

相关文章:

c# - TeamCity 代码覆盖率意外结果

java - 模块化项目中测试代码的实用打包

asp.net-mvc - 未找到与名为 'User' 的 Controller 匹配的类型

asp.net-mvc-3 - ASP.NET MVC 3 路由 : prevent ~/home access?

c# - 有没有办法为所有操作创建 CancellationToken 过滤器?

C# : How to keep track of each file added in a directory and log fileinfo into a file?

asp.net-mvc - 确保 View 存在

asp.net - 在每个操作上填充 ViewData,但不在渲染操作上填充 ViewData

C# NewtonSoft Single Object 或 Array JsonConverter 不工作,没有错误

c# - 如何评估 C# 中的自定义括号表达式?