使用HttpClient单元测试基于Unity的WebApi
webapi的单元测试,使用new controller的方式有些地方测试不到,比如过滤器啥的,
所以想用httpclient方式测试,模拟真正的链接,
但是在测试的时候遇到了一个问题,使用属性注入【Dependency】的时候无法注入,最后又换了构造器注入方式,也不知道怎么着属性注入与构造器注入都好了。。。 尴尬,记录一下吧
先上一波controller的代码:
[Dependency]
public IUserService Service { get; set; }
//private IUserService Service;
//public UserController(IUserService uservice)
//{
// Service = uservice;
//}
public async Task<IHttpActionResult> Get(string id)
{
var result = await Service.GetByIdAsync(id);
return Ok(result);
}
两种注入方式,一个简单的get方法
然后看单元测试(以下全为单元测试代码):
private string address = "https://localhost:44337";
private HttpClient client;
public UserControllerTests()
{
client = new HttpClient { BaseAddress = new Uri(address) };
}
[TestMethod()]
public async Task GetTestAsync()
{
using (WebApp.Start(address, Configuration))
{
var response = await client.GetAsync("api/user");
await AssertResponseNotNullAsync<List<User>>(response);
}
}
public async Task AssertResponseNotNullAsync<T>(HttpResponseMessage response)
{
if (response.IsSuccessStatusCode)
{
var model = await response.Content.ReadAsAsync<T>();
Assert.IsNotNull(model);
}
else
{
var str = await response.Content.ReadAsStringAsync();
Assert.Fail(str);
}
}
使用httpclient方式调用api,首先需要将api托起,使用owin方式(WebApp.Start)
Configuration配置 路由以及IOC的注入
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.DependencyResolver = UnityWebApiActivator.GetDependencyResolver();
app.UseWebApi(config);
}
在项目的UnityWebApiActivator类里面写了个获取Resolver的方法,很简单,也可以直接写到Configuration中
public static UnityDependencyResolver GetDependencyResolver()
{
return new UnityDependencyResolver(UnityConfig.Container);
}
最后贴一下引用:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using AccountManager.DB.Entity;
using Microsoft.Owin.Hosting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Owin;
另外Test项目需要安装WebApi.Owin、Owin、Owin.Hosting、Owin.Host.HttpListener、Unity.AspNet.WebApi的Nuget