WebAPI的一种单元测试方案
大家是如何对webApi写测试的呢?
1.利用Fiddler直接做请求,观察response的内容。
2.利用Httpclient做请求,断言response的内容。
3.直接调用webApi的action,这种方式的测试跟真实的调用还是有一定差距,不够完美。
接下来我介绍一种webApi的in-memory调用方法,也能够达到对webApi的测试,并且由于是in-memory调用,效率也比较高,非常适写单元测试。本文参考了In memory client, host and integration testing of your Web API service。
一、首先写一个OrderController用来做测试用
public class OrderController : ApiController
{
// GET api/order
public Order Get()
{
return new Order(){Id = 1,Descriptions = "descriptions",Name = "name"};
} // GET api/order/5
public string Get(int id)
{
return "value";
} // POST api/order
public Order Post(Order order)
{
return order;
} // DELETE api/order/5
public void Delete(int id)
{
}
}
二、WebApi的请求过程
webApi的核心是对消息的管道处理,整个核心是有一系列消息处理器(HttpMessageHandler)首尾连接的双向管道,管道头为HttpServer,管道尾为HttpControllerDispatcher,HttpControllerDispatcher负责对controller的激活和action的执行,然后相应的消息逆向流出管道。
所以我们可以利用HttpMessageInvoker将一个请求消息HttpRequestMessage发送到管道中,最后收到的消息HttpResponseMessage就代表一个真实的请求响应。
三、Get请求的测试
[Test]
public void GetTest()
{
string baseAddress = "http://localhost:33203/"; HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
HttpServer server = new HttpServer(config);
HttpMessageInvoker messageInvoker = new HttpMessageInvoker(server);
CancellationTokenSource cts = new CancellationTokenSource();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, baseAddress + "api/order"); using (HttpResponseMessage response = messageInvoker.SendAsync(request, cts.Token).Result)
{
var content = response.Content.ReadAsStringAsync().Result;
var result = JsonConvert.DeserializeObject<Order>(content); result.Name.Should().Be("name");
}
}
四、Post请求的测试
[Test]
public void PostTest()
{
string baseAddress = "http://localhost:33203/"; HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
HttpServer server = new HttpServer(config);
HttpMessageInvoker messageInvoker = new HttpMessageInvoker(server);
CancellationTokenSource cts = new CancellationTokenSource();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, baseAddress + "api/order");
var order = new Order() { Id = 1, Name = "orderName", Descriptions = "orderDescriptions" };
request.Content = new ObjectContent<Order>(order, new JsonMediaTypeFormatter());
using (HttpResponseMessage response = messageInvoker.SendAsync(request, cts.Token).Result)
{
var content = JsonConvert.SerializeObject(order, new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() });
response.Content.ReadAsStringAsync().Result.Should().Be(content);
}
}
四、重构
可以看到这两个测试大部分的代码是相同的,都是用来发送请求。因此我们提取一个webApiTestBase类,该基类可以提供InvokeGetRequest,InvokePostRequest,InvokePutRequest等方法
public abstract class ApiTestBase
{
public abstract string GetBaseAddress(); protected TResult InvokeGetRequest<TResult>(string api)
{
using (var invoker = CreateMessageInvoker())
{
using (var cts = new CancellationTokenSource())
{
var request = new HttpRequestMessage(HttpMethod.Get, GetBaseAddress() + api);
using (HttpResponseMessage response = invoker.SendAsync(request, cts.Token).Result)
{
var result = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<TResult>(result);
}
}
}
} protected TResult InvokePostRequest<TResult, TArguemnt>(string api, TArguemnt arg)
{
var invoker = CreateMessageInvoker();
using (var cts = new CancellationTokenSource())
{
var request = new HttpRequestMessage(HttpMethod.Post, GetBaseAddress() + api);
request.Content = new ObjectContent<TArguemnt>(arg, new JsonMediaTypeFormatter());
using (HttpResponseMessage response = invoker.SendAsync(request, cts.Token).Result)
{
var result = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<TResult>(result);
}
}
} private HttpMessageInvoker CreateMessageInvoker()
{
var config = new HttpConfiguration();
WebApiConfig.Register(config);
var server = new HttpServer(config);
var messageInvoker = new HttpMessageInvoker(server);
return messageInvoker;
}
}
有了这个基类,我们写测试只需要重写方法GetBaseAddress(),然后直接调用基类方法并进行断言即可
[TestFixture]
public class OrderApiTests:ApiTestBase
{
public override string GetBaseAddress()
{
return "http://localhost:33203/";
} [Test]
public void Should_get_order_successfully()
{
var result = InvokeGetRequest<Order>("api/order"); result.Name.Should().Be("name");
result.Descriptions.Should().Be("descriptions");
result.Id.Should().Be(1);
} [Test]
public void Should_post_order_successfully()
{
var newOrder=new Order(){Name = "newOrder",Id = 100,Descriptions = "new-order-description"}; var result = InvokePostRequest<Order,Order>("api/order", newOrder); result.Name.Should().Be("newOrder");
result.Id.Should().Be(100);
result.Descriptions.Should().Be("new-order-description");
}
}
是不是干净多了。
这种in-memory的测试方案有什么优点和缺点呢?
优点:
1.模拟真实调用,需要传入api地址即可得到结果,由于整个调用是in-memory的,所有效率很高,很适合集成测试。
2.整个测试时可以调试的,可以直接从单元测试调试进去,如果你写一个httpClient的测试,需要把webApi启动起来,然后。。。麻烦
缺点:我觉得原文作者说的那些缺点都可以忽略不计。
WebAPI的一种单元测试方案的更多相关文章
- WebApi的一种集成测试写法(in-memory)
WebApi的一种集成测试写法(in-memory) 大家是如何对webApi写测试的呢? 1.利用Fiddler直接做请求,观察response的内容. 2.利用Httpclient做请求,断言 ...
- 总结:视频播放的四种实现方案(Native)
一.来自 AVFoundation的 AVPlayer对象 特点: 1. AVPlayer > 优点: 可以自定义UI, 进行控制 > 缺点: ...
- 转【实战体验几种MySQLCluster方案】
实战体验几种MySQLCluster方案 1.背景 MySQL的cluster方案有很多官方和第三方的选择,选择多就是一种烦恼,因此,我们考虑MySQL数据库满足下三点需求,考察市面上可行的解决方案: ...
- 真正意义上的spring环境中的单元测试方案spring-test与mokito完美结合
真正意义上的spring环境中的单元测试方案spring-test与mokito完美结合 博客分类: java 测试 单元测试SpringCC++C# 一.要解决的问题: spring环境中 ...
- 第八节: Quartz.Net五大构件之SimpleThreadPool及其四种配置方案
一. 简介 揭秘: SimpleThreadPool是Quartz.Net中自带的线程池,默认个数为10个,代表一个Scheduler同一时刻并发的最多只能执行10个job,超过10个的job需要排队 ...
- [转CSDN多篇文章]WEB 3D SVG CAD 矢量 几种实现方案
WEB 3D SVG CAD 矢量 几种实现方案 原创 2014年10月24日 08:34:11 标签: WEB3D / CADSVG / 矢量 2665 一.全部自己开发,从底层开始 VML+SVG ...
- 分布式唯一ID的几种生成方案
前言 在互联网的业务系统中,涉及到各种各样的ID,如在支付系统中就会有支付ID.退款ID等.那一般生成ID都有哪些解决方案呢?特别是在复杂的分布式系统业务场景中,我们应该采用哪种适合自己的解决方案是十 ...
- 第九节: 利用RemoteScheduler实现Sheduler的远程控制 第八节: Quartz.Net五大构件之SimpleThreadPool及其四种配置方案 第六节: 六类Calander处理六种不同的时间场景 第五节: Quartz.Net五大构件之Trigger的四大触发类 第三节: Quartz.Net五大构件之Scheduler(创建、封装、基本方法等)和Job(创建、关联
第九节: 利用RemoteScheduler实现Sheduler的远程控制 一. RemoteScheduler远程控制 1. 背景: 在A服务器上部署了一个Scheduler,我们想在B服务器上 ...
- JavaScript常用八种继承方案
更新:在常用七种继承方案的基础之上增加了ES6的类继承,所以现在变成八种啦,欢迎加高级前端进阶群一起学习(文末). --- 2018.10.30 1.原型链继承 构造函数.原型和实例之间的关系:每个构 ...
随机推荐
- Windows cmd命令搜索顺序
一.在cmd中执行一个不带后缀的命令(不带路径),首先会在无后缀的系统命令(如cd.dir等)中搜索,如果找到了就执行该命令, (dir是无后缀的系统命令所以优先执行,无视当前目录中的dir.exe) ...
- 异步I/O操作
今天在看boost库的时候注意到异步I/O操作时,缓冲区有效性问题. 如何实现异步操作:以异步读操作为例async_read(buffer, handler): void handler() {} v ...
- Goals100
Start:2016.4.10 100天目标:jy_ai学习.swift.设计模式 以10天为周期,开始周会,执行内容:自我检讨本周期,并展望下一个周期:目标一:寻找高效方法.1.思考, ...
- 如何让电脑公司Win7系统自动关闭停止响应的程序
在注册表编辑器窗口左侧,依次展开HKEY_CURRENT_USER\ControlPanel\Desktop,选中Desktop,在右边的窗口中选择AutoEndTasks,双击打开AutoEndTa ...
- firefox的console log功能
http://www.ruanyifeng.com/blog/2011/03/firebug_console_tutorial.html Firebug是网页开发的利器,能够极大地提升工作效率. 但是 ...
- 深入研究C语言 第四篇
这里更多探究的是指针的机制. 用debug对下面程序进行分析,记录每一条C语句运行后,相关内存单元的值. 程序a.c 注意理解指针机制 我们编写如下代码: 编译加载进debug查看: 我们先看其反汇编 ...
- text-shadow文字阴影属性用法
text-shadow:offset-x:阴影水平移动,负值时向左偏移 text-shadow:offset-y:阴影垂直移动,负值时向上移动 text-shadow:radio-bluer:阴影到实 ...
- JS、C#及SQL中的DateTime
一:SQL中的DataTime 1. between and 相当于>= and <= 2. 常用的将DataTime查询成字符串的方法 Select CONVER ...
- webDriver环境搭建与测试
1.安装jdk 2.安装eclipse 3.安装selenium 由于使用的是开发语言是java,因此需要安装java版的selenium包.下载地址:http://pan.baidu.com/s/1 ...
- map容器的使用
1.map是STL容器中的一种,属于关联性容器.以key value的形式存储.key必须唯一.如果重复则插入失败.插入后按照key默认排序.必须要先声明命名空间:using namespace st ...