自动测试ApiController [英] Automatic testing of ApiController
问题描述
我有一个 ApiController
,并希望通过包含路由的单元测试对其进行测试.
I have an ApiController
and would like to test it with unit tests including the routing.
一个例子:
[RoutePrefix("prefix")]
public class Controller : ApiController
{
[HttpGet]
[Route("{id1}")]
public int Add(int id1, [FromUri] int id2)
{
return id1 + id2;
}
}
我现在要测试此方法.我知道,我可以像普通方法一样对其进行测试.但是我也想通过将URL转换为方法参数来对其进行测试.
I would now like to test this method. I see, that I can test it like an ordinary method. But I would also like to test it with the translation of the URL to the method parameters.
基本上,我想进行一次自动测试,在其中调用诸如 prefix/10?id2 = 5
之类的URL并得到结果15.这在某种程度上可能吗?
Basically I would like to have an automatic test where I call a URL like prefix/10?id2=5
and get a result of 15. Is this somehow possible?
推荐答案
我为内存集成测试编写了一个小帮助程序类,可以将其称为测试服的一部分.
I wrote a little helper class for in-memory integration testing that can be called as part of the test suit.
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进行调用.从本质上讲,它是一个端到端集成测试.
This will configure an in-memory test server that the test can make calls to using its httpclient. It is in essence an end-to-end integration test.
这篇关于自动测试ApiController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!