前面的文章,我们使用WCF构建一个简单的REST的WCF Service。之前我们使用Fiddler来测试,现在还可以使用WCF Web API来测试。代码看来起更加简洁
首先,你可从CODEPLEX下载,也可以从NuGet安装它,执行:

Install-Package netfx-WebApi.Testing

WCF HTTP高层架构是这样的:

wcfHttp 

基于上次的DEMO,我们使用来写一些UnitTest,传统方式我们不使用Proxy方式,使用ServiceHost和ChannelFactory,下面是测试Http-GET的方法

   1:          [TestMethod]
   2:          public void TestChannelFactoryWithWebHttpBinding2()
   3:          {
   4:              using (var myserviceHost = new ServiceHost(typeof(CRUDService), new Uri("http://localhost:20259/CRUDService.svc")))
   5:              {
   6:                  var binding = new WebHttpBinding();
   7:                  myserviceHost.AddServiceEndpoint(typeof(IDataService), binding, "").Behaviors.Add(new WebHttpBehavior());
   8:                  myserviceHost.Open();
   9:   
  10:                  using (ChannelFactory<IDataService> myChannelFactory = new ChannelFactory<IDataService>(new WebHttpBinding(), "http://localhost:20259/CRUDService.svc"))
  11:                  {
  12:                      myChannelFactory.Endpoint.Behaviors.Add(new WebHttpBehavior());
  13:   
  14:                      // Create a channel.
  15:                      IDataService wcfClient1 = myChannelFactory.CreateChannel();
  16:                      var employee = wcfClient1.Get(1);
  17:                      Assert.IsNotNull(employee);
  18:                      Assert.AreEqual(1,employee.EmployeeID);
  19:   
  20:                      ((IClientChannel)wcfClient1).Close();
  21:                      myChannelFactory.Close();
  22:                  }
  23:   
  24:                  myserviceHost.Close();
  25:              }
  26:          }
 
接下来我们使用WCF Web API来测试Service中CRUD的四个方法,对Create我使用是Http-POST,Delete是Http-DELETE,Update用的是Http-PUT,Get是Http-GET.
 
   1:      /// <summary>
   2:      /// CRUDServiceTest
   3:      /// </summary>
   4:      /// <remarks>
   5:      /// Author Petter Liu http://www.cnblogs.com/wintersun 
   6:      /// </remarks>
   7:      [TestClass]
   8:      public class CRUDServiceTest
   9:      {
  10:          #region Public Methods
  11:   
  12:          /// <summary>
  13:          /// The test create.
  14:          /// </summary>
  15:          [TestMethod]
  16:          public void TestCreate()
  17:          {
  18:              using (
  19:                  var webservice = new HttpWebService<CRUDService>(
  20:                      serviceBaseUrl: "http://localhost:20259", 
  21:                      serviceResourcePath: "CRUDService.svc", 
  22:                      serviceConfiguration: HttpHostConfiguration.Create()))
  23:              {
  24:                  var client = new HttpClient(webservice.BaseUri);
  25:   
  26:                  // Builds: http://localhost:20259/CRUDService.svc/Create
  27:                  Uri uri = webservice.Uri("Create");
  28:   
  29:                  var employee = new Employee
  30:                      {
  31:                          ContactID = 1, 
  32:                          ManagerID = 23, 
  33:                          Title = "Engineer", 
  34:                          Gender = "1", 
  35:                          CurrentFlag = false, 
  36:                          NationalIDNumber = "32323"
  37:                      };
  38:   
  39:                  var httpcontent = new FormUrlEncodedContent(this.GetEntityToListKeyValuePair(employee));
  40:                  HttpResponseMessage response = client.Post(uri, httpcontent);
  41:   
  42:                  Assert.IsTrue(response.IsSuccessStatusCode, response.ToString());
  43:                  Assert.IsTrue(response.Content.ReadAsString().Contains("true"));
  44:              }
  45:          }
  46:   
  47:          /// <summary>
  48:          /// The test delete.
  49:          /// </summary>
  50:          [TestMethod]
  51:          public void TestDelete()
  52:          {
  53:              using (
  54:                  var webservice = new HttpWebService<CRUDService>(
  55:                      serviceBaseUrl: "http://localhost:20259", 
  56:                      serviceResourcePath: "CRUDService.svc", 
  57:                      serviceConfiguration: HttpHostConfiguration.Create()))
  58:              {
  59:                  var client = new HttpClient(webservice.BaseUri);
  60:   
  61:                  // Builds: http://localhost:20259/CRUDService.svc/Del?id=1
  62:                  Uri uri = webservice.Uri("Del?id=1");
  63:   
  64:                  HttpResponseMessage response = client.Delete(uri);
  65:   
  66:                  Assert.IsTrue(response.IsSuccessStatusCode, response.ToString());
  67:                  Assert.IsTrue(response.Content.ReadAsString().Contains("true"));
  68:              }
  69:          }
  70:   
  71:          /// <summary>
  72:          /// Test get.
  73:          /// </summary>
  74:          [TestMethod]
  75:          public void TestGet()
  76:          {
  77:              using (
  78:                  var webservice = new HttpWebService<CRUDService>(
  79:                      serviceBaseUrl: "http://localhost:20259", 
  80:                      serviceResourcePath: "CRUDService.svc", 
  81:                      serviceConfiguration: HttpHostConfiguration.Create()))
  82:              {
  83:                  var client = new HttpClient(webservice.BaseUri);
  84:   
  85:                  // Builds: http://localhost:20259/CRUDService.svc/Get?id=1
  86:                  Uri uri = webservice.Uri("Get?id=1");
  87:                  HttpResponseMessage response = client.Get(uri);
  88:   
  89:                  Assert.IsTrue(response.IsSuccessStatusCode, response.ToString());
  90:   
  91:                  // Console.WriteLine(response.Content.ReadAsString());
  92:                  Assert.IsTrue(response.Content.ReadAsString().Contains("11"));
  93:              }
  94:          }
  95:   
  96:          /// <summary>
  97:          /// Test update.
  98:          /// </summary>
  99:          [TestMethod]
 100:          public void TestUpdate()
 101:          {
 102:              using (
 103:                  var webservice = new HttpWebService<CRUDService>(
 104:                      serviceBaseUrl: "http://localhost:20259", 
 105:                      serviceResourcePath: "CRUDService.svc", 
 106:                      serviceConfiguration: HttpHostConfiguration.Create()))
 107:              {
 108:                  var client = new HttpClient(webservice.BaseUri);
 109:   
 110:                  // Builds: http://localhost:20259/CRUDService.svc/Update?id=1
 111:                  Uri uri = webservice.Uri("Update?id=1");
 112:   
 113:                  // fake http content
 114:                  var keyvalus = new List<KeyValuePair<string, string>>();
 115:                  keyvalus.Add(new KeyValuePair<string, string>("employeeId", "1"));
 116:                  HttpResponseMessage response = client.Put(uri, new FormUrlEncodedContent(keyvalus));
 117:   
 118:                  Assert.IsTrue(response.IsSuccessStatusCode, response.ToString());
 119:                  Assert.IsTrue(response.Content.ReadAsString().Contains("true"));
 120:              }
 121:          }
 122:   
 123:          #endregion
 124:   
 125:          #region Private Helper Methods
 126:   
 127:          /// <summary>
 128:          /// The get entity to list key value pair.
 129:          /// </summary>
 130:          /// <param name="employee">
 131:          /// The employee.
 132:          /// </param>
 133:          /// <returns>
 134:          /// </returns>
 135:          private List<KeyValuePair<string, string>> GetEntityToListKeyValuePair(Employee employee)
 136:          {
 137:              var keyvalus = new List<KeyValuePair<string, string>>();
 138:   
 139:              foreach (PropertyInfo po in
 140:                  employee.GetType().GetProperties())
 141:              {
 142:                  object rr = po.GetValue(employee, null);
 143:   
 144:                  if (rr != null)
 145:                  {
 146:                      // parse datatime and guid and bool type has some issue
 147:                      if (!rr.ToString().Contains('/') && !rr.ToString().Contains('-') && !rr.ToString().Contains("False"))
 148:                      {
 149:                          keyvalus.Add(new KeyValuePair<string, string>(po.Name, rr.ToString()));
 150:                          Console.WriteLine("{0}:  {1}", po.Name, rr);
 151:                      }
 152:                  }
 153:              }
 154:   
 155:              return keyvalus;
 156:          }
 157:   
 158:          #endregion
 159:      }

上面的代码中,ServiceBaseUrl指定就是Endpoint的address了,注意测试时我们并不需要事先创建ServiceHost。你可以有使用过WebServiceHost,这里使用是HttpWebService,区别在于后者是经过Http pipe API的.

希望这篇POST对您开发有帮助。


作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog

posted on 2011-07-01 13:48  PetterLiu  阅读(2226)  评论(2编辑  收藏  举报