WebApi单元测试记录
一、MessageHandler不一定是全局的,也可以只应用到指定的Router上
1、定义一个handler // Pipelines HttpMessageHandler affiliateShipmentsPipeline = HttpClientFactory.CreatePipeline( new HttpControllerDispatcher(config), new[] { new AffiliateShipmentsDispatcher() }); 2、将handler应用在指定的router上 // Routes routes.MapHttpRoute( "AffiliateShipmentsHttpRoute", "api/affiliates/{key}/shipments/{shipmentKey}", defaults: new { controller = "AffiliateShipments", shipmentKey = RouteParameter.Optional }, constraints: new { key = new GuidRouteConstraint(), shipmentKey = new GuidRouteConstraint() }, handler: affiliateShipmentsPipeline);
二、HttpRequest头添加Authorization信息
HttpRequestMessage request = ConstructRequest(httpMethod, uri, mediaTypes); request.Headers.Authorization = new AuthenticationHeaderValue( "Basic", EncodeToBase64( string.Format("{0}:{1}", username, password))); private static string EncodeToBase64(string value) { byte[] toEncodeAsBytes = Encoding.UTF8.GetBytes(value); return Convert.ToBase64String(toEncodeAsBytes); }
三、模拟异步发送Http请求
internal static async Task<HttpResponseMessage> GetResponseAsync( HttpConfiguration config, HttpRequestMessage request) { using (var httpServer = new HttpServer(config)) using (var client = HttpClientFactory.Create(innerHandler: httpServer)) { return await client.SendAsync(request); } }
四、模拟WebApi HttpRequestMessage的Content
request.Content = new ObjectContent<ShipmentRequestModel>( shipmentRequestModel, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
五、HttpRequestMessage对象获取依赖注入接口
internal static class HttpRequestMessageExtensions { internal static IShipmentService GetShipmentService(this HttpRequestMessage request) { return request.GetServic e<IShipmentService>(); } internal static IMembershipService GetMembershipService(this HttpRequestMessage request) { return request.GetService<IMembershipService>(); } private static TService GetService<TService>(this HttpRequestMessage request) { IDependencyScope dependencyScope = request.GetDependencyScope(); TService service = (TService)dependencyScope.GetService(typeof(TService)); return service; } }