gpt4 book ai didi

c# - ApiController 的自动测试

转载 作者:行者123 更新时间:2023-11-30 19:54:54 25 4
gpt4 key购买 nike

我有一个 ApiController 并想用包括路由在内的单元测试来测试它。

一个例子:

[RoutePrefix("prefix")]
public class Controller : ApiController
{
[HttpGet]
[Route("{id1}")]
public int Add(int id1, [FromUri] int id2)
{
return id1 + id2;
}
}

我现在想测试这个方法。我明白了,我可以像普通方法一样测试它。但我也想通过将 URL 转换为方法参数来测试它。

基本上我想要一个自动测试,我调用一个像 prefix/10?id2=5 这样的 URL 并得到 15 的结果。这在某种程度上可能吗?

最佳答案

我为内存中的集成测试编写了一个小助手类,可以将其作为测试套件的一部分调用。

internal interface IHttpTestServer : IDisposable {
HttpConfiguration Configuration { get; }
HttpClient CreateClient();
}

internal class HttpTestServer : IHttpTestServer {
HttpServer httpServer;

public HttpTestServer(HttpConfiguration configuration = null) {
httpServer = new HttpServer(configuration ?? new HttpConfiguration());
}

public HttpConfiguration Configuration {
get { return httpServer.Configuration; }
}

public HttpClient CreateClient() {
var client = new HttpClient(httpServer);
return client;
}

public void Dispose() {
if (httpServer != null) {
httpServer.Dispose();
httpServer = null;
}
}

public static IHttpTestServer Create(HttpConfiguration configuration = null) {
return new HttpTestServer(configuration);
}
}

然后会像这样使用它

[TestMethod]
public async Task HttpClient_Should_Get_OKStatus_From_InMemory_Hosting() {

using (var server = new HttpTestServer()) {

MyWebAPiProjectNamespace.WebApiConfig.Configure(server.Configuration);

var client = server.CreateClient();

string url = "http://localhost/prefix/10?id2=5";
var expected = 15;

var request = new HttpRequestMessage {
RequestUri = new Uri(url),
Method = HttpMethod.Get
};

request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

using (var response = await client.SendAsync(request)) {
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
var result = await response.Content.ReadAsAsync<int>();
Assert.AreEqual(expected, result);
}
}
}

这将配置一个内存中的测试服务器,测试可以使用其 httpclient 调用该服务器。它本质上是一个端到端的集成测试。

关于c# - ApiController 的自动测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40423823/

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