在owin中,可以使用TestServer在单元测试中测试Web api(请参阅blog)。
此功能可用于asp.net 5中间件吗?
更新:
根据下面的响应,我尝试使用TestServer,但是visual studio提示'类型或 namespace 名称'AspNet'在 namespace 'Microsoft'中不存在(是您.....'
(我也尝试过https://www.myget.org/F/aspnetvnext/,但是遇到了同样的问题)
{
"version": "1.0.0-*",
"dependencies": {
"Microsoft.AspNet.Http": "1.0.0-*",
"Microsoft.AspNet.TestHost": "1.0.0-*",
"Microsoft.AspNet.Hosting": "1.0.0-*",
"Microsoft.AspNet.Testing" : "1.0.0-*",
"xunit": "2.1.0-beta1-*",
"xunit.runner.aspnet": "2.1.0-beta1-*",
"Moq": "4.2.1312.1622",
"Shouldly": "2.4.0"
},
"commands": {
"test": "xunit.runner.aspnet"
},
"frameworks" : {
"aspnet50" : {
"dependencies": {
}
}
}
}
最佳答案
它也可以在ASP.NET 5上使用:Microsoft.AspNet.TestHost。
这是一个样本。中间件:
public class DummyMiddleware
{
private readonly RequestDelegate _next;
public DummyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
Console.WriteLine("DummyMiddleware");
context.Response.ContentType = "text/html";
context.Response.StatusCode = 200;
await context.Response.WriteAsync("hello world");
}
}
测试:
[Fact]
public async Task Should_give_200_Response()
{
var server = TestServer.Create((app) =>
{
app.UseMiddleware<DummyMiddleware>();
});
using(server)
{
var response = await server.CreateClient().GetAsync("/");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
您可以在TestServer上找到有关the tests类的用法的更多信息。