您的位置:首页 > 其它

使用WCF web API测试基于REST的WCF Service

2011-07-01 13:48 453 查看
前面的文章,我们使用WCF构建一个简单的REST的WCFService。之前我们使用Fiddler来测试,现在还可以使用WCFWebAPI来测试。代码看来起更加简洁
首先,你可从CODEPLEX下载,也可以从NuGet安装它,执行:

Install-Packagenetfx-WebApi.Testing

WCFHTTP高层架构是这样的:





基于上次的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;}


接下来我们使用WCFWebAPI来测试Service中CRUD的四个方法,对Create我使用是Http-POST,Delete是Http-DELETE,Update用的是Http-PUT,Get是Http-GET.

///<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/Create
Uriuri=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=1
Uriuri=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=1
Uriuri=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=1
Uriuri=webservice.Uri("Update?id=1");
//fakehttpcontent
varkeyvalus=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(PropertyInfopoin
employee.GetType().GetProperties())
{
objectrr=po.GetValue(employee,null);
if(rr!=null)
{
//parsedatatimeandguidandbooltypehassomeissue
if(!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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
章节导航