ASP.NET 5 Web Api 集成测试
一、在测试项目中引用Web Api项目
引用Web Api项目的目的是使用Startup类,在Startup类中重载Configure方法,代码如下: ```csharp public void Configure(IApplicationBuilder app) { // Configure the HTTP request pipeline. app.UseStaticFiles();// Add MVC to the request pipeline.
app.UseMvc();
}
<h2>二、测试项目中安装需要的包</h2>
project.json中依赖包如下
```javascript
//略去所需的项目以来
"Microsoft.AspNet.Hosting": "1.0.0-beta8",
"Microsoft.AspNet.Mvc": "6.0.0-beta8",
"Microsoft.AspNet.StaticFiles": "1.0.0-beta8",
"Microsoft.AspNet.TestHost": "1.0.0-beta8",
"Microsoft.Framework.DependencyInjection": "1.0.0-beta8",
"xunit": "2.1.0",
"xunit.runner.dnx": "2.1.0-beta6-build191"
三、编写集成测试类
```csharp public class YourTestClass { private readonly Actionpublic WealthApiTest()
{
var startup = new Startup(new HostingEnvironment()); // 使用Web Api项目中的Startup类
_app = startup.Configure; // 将第一步中重载的Configure方法赋给_app委托
_services = startup.ConfigureServices;
}
// 单独的测试方法
}
<h2>四、编写测试方法</h2>
第三步已经做好了编写测试方法的准备,下面展示一个简单的get请求的测试
```csharp
[Fact]
public async Task GetByIdTest()
{
// Arrange
var server = TestServer.Create(_app, _services);
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/YourController/1");
var deserialized = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}