gpt4 book ai didi

c# - ASP.NET 单元测试不映射路由

转载 作者:太空宇宙 更新时间:2023-11-03 12:29:08 24 4
gpt4 key购买 nike

我有一个 Web API 项目,我想用单元测试来测试它。

在测试类中我创建了一个 HttpClient应该将 HTTP 调用直接重定向到我的 Controller :

public static HttpClient GetInMemoryServerClient(HttpConfiguration serverConfig)
{
var config = serverConfig ?? new HttpConfiguration();
MyService.WebApiConfig.Register(config, isTest: true);
var server = new HttpServer();
server.Configuration.Services.Replace(typeof(IHttpActionInvoker), server.Configuration.Services.GetActionInvoker());
return new HttpClient(server) { BaseAddress = new Uri("http://fakehost:9999/") };
}

在服务项目中,我有一个调用 config.MapHttpAttributeRoutes() 的类,它在产品中有效,但在测试调用时无效:

public class WebApiConfig{
//...
public static void Register(HttpConfiguration config) // this is called in Global.asax.cs
{
Register(config, false);
}

public static Register(HttpConfiguration config, bool isTest){
//... various config and dependency injection setup here
config.MapHttpAttributeRoutes();
}
}

我的 Controller 使用属性路由:

[RoutePrefix("api/groups/{groupId}/sets/{setId:minlength(1)}/items")]
public class ItemsController : BaseController
{
[Route("{itemId:minlength(1)}")]
[HttpGet]
public async Task<API.Item> Get(string groupId, string setId, string itemId)
{...}
}

当我使用 HttpClient调用我

{"Message":"No HTTP resource was found that matches the request URI 'http://fakehost:9999/api/groups/abc/sets/xyz/items/item123'."}

并检查 httpClient使用调试器我看到 httpClient.handler.Configuration.Routes.Count == 0 , 所以映射路由属性不起作用

问:设置假HttpClient的正确方法是什么?所以我的单元测试可以使用它来调用 Controller ?

最佳答案

HttpConfiguration config 未分配给服务器,因此未应用设置。该方法将映射应用于配置,但在初始化时未将配置分配给服务器。

public static HttpClient GetInMemoryServerClient(HttpConfiguration serverConfig = null) {
var config = serverConfig ?? new HttpConfiguration();
MyService.WebApiConfig.Register(config, isTest: true);
var server = new HttpServer(config); //<-- pass config to server
var client = new HttpClient(server);
//Server defaults to localhost so setting client to localhost as well
client.BaseAddress = new Uri("http://localhost");
return client;
}

在测试中,客户端可以像这样调用

using(var client = GetInMemoryServerClient()) {
var url = "api/groups/abc/sets/xyz/items/item123";
var response = await client.GetAsync(url);
//...do something with response
}

关于c# - ASP.NET 单元测试不映射路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43503754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com