使用WCF web API测试基于REST的WCF Service
2011-07-01 13:48
453 查看
前面的文章,我们使用WCF构建一个简单的REST的WCFService。之前我们使用Fiddler来测试,现在还可以使用WCFWebAPI来测试。代码看来起更加简洁
首先,你可从CODEPLEX下载,也可以从NuGet安装它,执行:
Install-Packagenetfx-WebApi.Testing
WCFHTTP高层架构是这样的:首先,你可从CODEPLEX
基于上次的DEMO,我们使用来写一些UnitTest,传统方式我们不使用Proxy方式,使用ServiceHost和ChannelFactory,下面是测试Http-GET的方法
[TestMethod]
publicvoidTestChannelFactoryWithWebHttpBinding2()
{
using(varmyserviceHost=newServiceHost(typeof(CRUDService),newUri("http://localhost:20259/CRUDService.svc")))
{
varbinding=newWebHttpBinding();
myserviceHost.AddServiceEndpoint(typeof(IDataService),binding,"").Behaviors.Add(newWebHttpBehavior());
myserviceHost.Open();
using(ChannelFactory<IDataService>myChannelFactory=newChannelFactory<IDataService>(newWebHttpBinding(),"http://localhost:20259/CRUDService.svc"))
{
myChannelFactory.Endpoint.Behaviors.Add(newWebHttpBehavior());
//Createachannel.
IDataServicewcfClient1=myChannelFactory.CreateChannel();
varemployee=wcfClient1.Get(1);
Assert.IsNotNull(employee);
Assert.AreEqual(1,employee.EmployeeID);
((IClientChannel)wcfClient1).Close();
myChannelFactory.Close();
}
myserviceHost.Close();
}
}
.csharpcode,.csharpcodepre
{
font-size:small;
color:black;
font-family:consolas,"CourierNew",courier,monospace;
background-color:#ffffff;
/*white-space:pre;*/
}
.csharpcodepre{margin:0em;}
.csharpcode.rem{color:#008000;}
.csharpcode.kwrd{color:#0000ff;}
.csharpcode.str{color:#006080;}
.csharpcode.op{color:#0000c0;}
.csharpcode.preproc{color:#cc6633;}
.csharpcode.asp{background-color:#ffff00;}
.csharpcode.html{color:#800000;}
.csharpcode.attr{color:#ff0000;}
.csharpcode.alt
{
background-color:#f4f4f4;
width:100%;
margin:0em;
}
.csharpcode.lnum{color:#606060;}
///<summary>
///CRUDServiceTest
///</summary>
///<remarks>
///AuthorPetterLiuhttp://www.cnblogs.com/wintersun
///</remarks>
[TestClass]
publicclassCRUDServiceTest
{
#regionPublicMethods
///<summary>
///Thetestcreate.
///</summary>
[TestMethod]
publicvoidTestCreate()
{
using(
varwebservice=newHttpWebService<CRUDService>(
serviceBaseUrl:"http://localhost:20259",
serviceResourcePath:"CRUDService.svc",
serviceConfiguration:HttpHostConfiguration.Create()))
{
varclient=newHttpClient(webservice.BaseUri);
//Builds: 'target='_blank'>http://localhost:20259/CRUDService.svc/CreateUriuri=webservice.Uri("Create");varemployee=newEmployee{ContactID=1,ManagerID=23,Title="Engineer",Gender="1",CurrentFlag=false,NationalIDNumber="32323"};varhttpcontent=newFormUrlEncodedContent(this.GetEntityToListKeyValuePair(employee));HttpResponseMessageresponse=client.Post(uri,httpcontent);Assert.IsTrue(response.IsSuccessStatusCode,response.ToString());Assert.IsTrue(response.Content.ReadAsString().Contains("true"));}}///<summary>///Thetestdelete.///</summary>[TestMethod]publicvoidTestDelete(){using(varwebservice=newHttpWebService<CRUDService>(serviceBaseUrl:"http://localhost:20259",serviceResourcePath:"CRUDService.svc",serviceConfiguration:HttpHostConfiguration.Create())){varclient=newHttpClient(webservice.BaseUri);//Builds: 'target='_blank'>http://localhost:20259/CRUDService.svc/Del?id=1Uriuri=webservice.Uri("Del?id=1");HttpResponseMessageresponse=client.Delete(uri);Assert.IsTrue(response.IsSuccessStatusCode,response.ToString());Assert.IsTrue(response.Content.ReadAsString().Contains("true"));}}///<summary>///Testget.///</summary>[TestMethod]publicvoidTestGet(){using(varwebservice=newHttpWebService<CRUDService>(serviceBaseUrl:"http://localhost:20259",serviceResourcePath:"CRUDService.svc",serviceConfiguration:HttpHostConfiguration.Create())){varclient=newHttpClient(webservice.BaseUri);//Builds: 'target='_blank'>http://localhost:20259/CRUDService.svc/Get?id=1Uriuri=webservice.Uri("Get?id=1");HttpResponseMessageresponse=client.Get(uri);Assert.IsTrue(response.IsSuccessStatusCode,response.ToString());//Console.WriteLine(response.Content.ReadAsString());Assert.IsTrue(response.Content.ReadAsString().Contains("11"));}}///<summary>///Testupdate.///</summary>[TestMethod]publicvoidTestUpdate(){using(varwebservice=newHttpWebService<CRUDService>(serviceBaseUrl:"http://localhost:20259",serviceResourcePath:"CRUDService.svc",serviceConfiguration:HttpHostConfiguration.Create())){varclient=newHttpClient(webservice.BaseUri);//Builds: 'target='_blank'>http://localhost:20259/CRUDService.svc/Update?id=1Uriuri=webservice.Uri("Update?id=1");//fakehttpcontentvarkeyvalus=newList<KeyValuePair<string,string>>();keyvalus.Add(newKeyValuePair<string,string>("employeeId","1"));HttpResponseMessageresponse=client.Put(uri,newFormUrlEncodedContent(keyvalus));Assert.IsTrue(response.IsSuccessStatusCode,response.ToString());Assert.IsTrue(response.Content.ReadAsString().Contains("true"));}}#endregion#regionPrivateHelperMethods///<summary>///Thegetentitytolistkeyvaluepair.///</summary>///<paramname="employee">///Theemployee.///</param>///<returns>///</returns>privateList<KeyValuePair<string,string>>GetEntityToListKeyValuePair(Employeeemployee){varkeyvalus=newList<KeyValuePair<string,string>>();foreach(PropertyInfopoinemployee.GetType().GetProperties()){objectrr=po.GetValue(employee,null);if(rr!=null){//parsedatatimeandguidandbooltypehassomeissueif(!rr.ToString().Contains('/')&&!rr.ToString().Contains('-')&&!rr.ToString().Contains("False")){keyvalus.Add(newKeyValuePair<string,string>(po.Name,rr.ToString()));Console.WriteLine("{0}:{1}",po.Name,rr);}}}returnkeyvalus;}#endregion}
.csharpcode,.csharpcodepre
{
font-size:small;
color:black;
font-family:consolas,"CourierNew",courier,monospace;
background-color:#ffffff;
/*white-space:pre;*/
}
.csharpcodepre{margin:0em;}
.csharpcode.rem{color:#008000;}
.csharpcode.kwrd{color:#0000ff;}
.csharpcode.str{color:#006080;}
.csharpcode.op{color:#0000c0;}
.csharpcode.preproc{color:#cc6633;}
.csharpcode.asp{background-color:#ffff00;}
.csharpcode.html{color:#800000;}
.csharpcode.attr{color:#ff0000;}
.csharpcode.alt
{
background-color:#f4f4f4;
width:100%;
margin:0em;
}
.csharpcode.lnum{color:#606060;}
上面的代码中,ServiceBaseUrl指定就是Endpoint的address了,注意测试时我们并不需要事先创建ServiceHost。你可以有使用过WebServiceHost,这里使用是HttpWebService,区别在于后者是经过HttppipeAPI的.
希望这篇POST对您开发有帮助。
作者:PetterLiu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-PetterLiuBlog。
相关文章推荐
- Difference between WCF and Web API and WCF REST and Web Service[转]
- Difference between WCF and Web API and WCF REST and Web Service
- Python Web中REST API使用示例——基于云平台+云服务打造自己的在线翻译工具
- Difference between WCF and Web API and WCF REST and Web Service
- Difference between WCF and Web API and WCF REST and Web Service
- Web Service vs WCF vs WCF REST vs Web API
- Swagger-UI 基于REST的API测试/文档类插件
- 客户端使用gsoap,访问基于jax-ws框架的java webservice
- 使用 Swagger 自动生成 ASP.NET Core Web API 的文档、在线帮助测试文档(ASP.NET Core Web API 自动生成文档)
- 使用 Selenium 实现基于 Web 的自动化测试
- Node.js中REST API使用示例——基于云平台+云服务打造自己的在线翻译工具
- opendaylight web service REST api
- nodejs实战:使用原生nodeJs模块实现静态文件及REST请求解析及响应(基于nodejs6.2.0版本,不使用express等webMVC框架 )
- ios 使用webservice restful api使用ASIHttpRequest即可,restKit较大,可放后
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【九】——API变了,客户端怎么办?
- ASP.NET WEB API构建基于REST风格
- 使用JMETER做Webservice Security(WSS)测试
- Laravel 5 中使用 JWT(Json Web Token) 实现基于API的用户认证
- 就是这么简单!使用Rest-assured 测试Restful Web Services