Asp.net WebAPI单元测试
作者:网络转载 发布时间:[ 2016/5/10 14:38:22 ] 推荐标签:软件测试 单元测试
单元测试的code 如下:
public void TestPostArticle()
{
var article = new Article
{
Title = "Web API Unit Testing",
URL = "https://chsakell.com/web-api-unit-testing",
Author = "Chris Sakellarios",
DateCreated = DateTime.Now,
Contents = "Unit testing Web API.."
};
var _articlesController = new ArticlesController(_articleService)
{
Configuration = new HttpConfiguration(),
Request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("http://localhost/api/articles")
}
};
var result = _articlesController.PostArticle(article) as CreatedAtRouteNegotiatedContentResult<Article>;
Assert.That(result.RouteName, Is.EqualTo("DefaultApi"));
Assert.That(result.Content.ID, Is.EqualTo(result.RouteValues["id"]));
Assert.That(result.Content.ID, Is.EqualTo(_randomArticles.Max(a => a.ID)));
}
在controller的实例的时候直接传递IArticleService 实例。
public static IArticleService GetIArticleService()
{
var _article = new Mock<IArticleService>();
_article.Setup(x => x.GetArticles(It.IsAny<string>())).Returns(new Func<string, List<Article>>(name =>
{
if (string.IsNullOrEmpty(name))
{
return _randomArticles;
}
else
{
return _randomArticles.FindAll(x => x.Title.Contains(name));
}
}));
_article.Setup(x => x.GetArticle(It.IsAny<int>())).Returns(new Func<int, Article>(id =>
{
return _randomArticles.Find(x => x.ID == id);
}));
_article.Setup(x => x.GetArticle(It.IsAny<string>())).Returns(new Func<string, Article>(name =>
{
return _randomArticles.Find(x => x.Title == name);
}));
_article.Setup(r => r.CreateArticle(It.IsAny<Article>()))
.Callback(new Action<Article>(newArticle =>
{
newArticle.DateCreated = DateTime.Now;
newArticle.ID = _randomArticles.Last().ID + 1;
_randomArticles.Add(newArticle);
}));
_article.Setup(r => r.UpdateArticle(It.IsAny<Article>()))
.Callback(new Action<Article>(x =>
{
var oldArticle = _randomArticles.Find(a => a.ID == x.ID);
oldArticle.DateEdited = DateTime.Now;
oldArticle.URL = x.URL;
oldArticle.Title = x.Title;
oldArticle.Contents = x.Contents;
oldArticle.BlogID = x.BlogID;
}));
return _article.Object;
}
由于WebApi一般都是用来提供接口的,使用者往往是以发送http请求来获取数据,我们也可以用这种方式来做单元测试:
public void TestPostArticle2()
{
var article = new Article
{
Title = "Web API Unit Testing2",
URL = "https://chsakell.com/web-api-unit-testing",
Author = "Chris Sakellarios",
DateCreated = DateTime.Now,
Contents = "Unit testing Web API.."
};
var address = "http://localhost:9000/";
using (WebApp.Start<Startup>(address))
{
HttpClient _client = new HttpClient();
var response = _client.PostAsJsonAsync<Article>(address + "api/articles/", article).Result;
var result = response.Content.ReadAsAsync<Article>().Result;
Assert.That(result.Title, Is.EqualTo(article.Title));
Assert.That(_randomArticles.Last().Title, Is.EqualTo(article.Title));
}
}
那么我们如何托起这个web 程序,有如何 使用IOC,
这里IOC 用Autofac,其所用包如下:
Install-Package Owin
Install-Package Microsoft.AspNet.WebApi.Owin
Install-Package Microsoft.Owin.Host.HttpListener
Install-Package Microsoft.Owin.Hosting
Install-Package Autofac
Install-Package Autofac.WebApi2
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
var config = new HttpConfiguration();
// config.Services.Replace(typeof(IAssembliesResolver), new CustomAssembliesResolver());
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var builder = new ContainerBuilder();
builder.RegisterApiControllers(typeof(ArticlesController).Assembly);
var _articleService = Helper.GetIArticleService();
builder.RegisterInstance(_articleService).As<IArticleService>();
IContainer container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
appBuilder.UseWebApi(config);
}
}
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系SPASVO小编(021-61079698-8054),我们将立即处理,马上删除。
相关推荐
iOS单元测试mocha、chai、sinon和istanbul实现百分之百的单元测试覆盖率关于单元测试的总结及思考编写更好的Java单元测试的7个技巧Android单元测试框架Robolectric3.0介绍(一)使用Kiwi单元测试总结单元测试如此重要,为什么你不知道Python单元测试??使用装饰器实现测试跳过和预期故障对Controller的单元测试写好单元测试的10个技巧单元测试的重要性Angular单元测试系列??Component、Directive、Pipe 以及ServiceAndroid单元测试的整理提升单元测试体验的利器--Mockito使用总结iOS UnitTest单元测试Vue的单元测试探索(二)
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11热门文章
常见的移动App Bug??崩溃的测试用例设计如何用Jmeter做压力测试QC使用说明APP压力测试入门教程移动app测试中的主要问题jenkins+testng+ant+webdriver持续集成测试使用JMeter进行HTTP负载测试Selenium 2.0 WebDriver 使用指南