C# WebApi 接口测试工具:WebApiTestClient应用技术详解

打印 上一主题 下一主题

主题 1929|帖子 1929|积分 5787

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
目录
一、引言      
二、WebApiTestClient介绍
1、特性
2、应用场景
三、WebApiTestClient具体利用
1、WebApi项目引入组件
2、怎样利用组件
 1、修改Api.cshtml文件
2、设置读取注释的xml路径
3、测试接口
四、总结


一、引言      

         由于近来项目需要开发WebApi接口,接口开发完了需要自测或提供给第三方进行调试,看了网上的方法,大多都是利用第三方测试工具,如Postman、Fiddler等,但这些固然功能强大,但利用起来较为繁琐,如Postman还需要注册、下载及安装等,因此就搜索其他的调试方法,如WebApiTestClient和swagger,这些都是轻量级的,可直接集成在项目中利用,很方便,本文主要介绍在WebApi中利用WebApiTestClien接口测试工具的应用。
二、WebApiTestClient介绍

        WebApiTestClient是一款专门为调试和测试ASP.NET WebApi设计的工具,可以通过简洁的Web界面发送哀求并检察相应。在API开发过程中,它可以帮助开发者更高效地进行调试和验证。
1、特性


  • 简洁的Web界面:无需额外安装复杂的工具,通过Web浏览器即可访问和利用。
  • 易于集成:作为NuGet包,可以方便地集成到现有的ASP.NET WebApi项目中。
  • 机动的哀求设置:可以自界说HTTP方法、哀求头、哀求体等,便于模拟各种哀求场景。
  • 实时检察相应:即时检察API的相应,包罗状态码、相应头和相应体,便于调试。

2、应用场景

1)开发阶段的调试
在开发阶段,WebApiTestClient可以用于快速验证API是否按预期工作。通过其简洁的界面,可以轻松构造各种HTTP哀求并检察相应,便于发现和修复标题。
2)测试API端点
在测试阶段,QA工程师可以利用WebApiTestClient模拟各种哀求,验证API的稳固性和精确性。能够自界说哀求参数和哀求体,也有助于进行边界测试和非常处理测试。
3)与前端开发的协同
前后端分离的开发模式下,前端开发人员可以利用WebApiTestClient测试后端API的接口,确保数据交互的精确性,减少前后端联调的时间和成本。
4)快速验证和演示
在需求评审或技术交换过程中,开发者可以利用WebApiTestClient进行快速验证和演示,展示API的功能和数据交互过程,提高沟通服从。
 
三、WebApiTestClient具体利用

1、WebApi项目引入组件

首先,我们需要界说一个API项目


然后通过Nuget引入组件,如下图。记着选下图中的第一个WebApiTestClient进行安装。

引入成功后,将向项目内里添加一些主要文件:


  • Scripts\WebApiTestClient.js
  • Areas\HelpPage\TestClient.css
  • Areas\HelpPage\Views\Help\DisplayTemplates\TestClientDialogs.cshtml
  • Areas\HelpPage\Views\Help\DisplayTemplates\TestClientReferences.cshtml
2、怎样利用组件

 1、修改Api.cshtml文件

通过上述步骤,就能将组件WebAPITestClient引入进来。下面我们只需要做一件事:打开文件 (根据 Areas\HelpPage\Views\Help) Api.cshtml 并添加以下内容:


  • @Html.DisplayForModel("TestClientDialogs")
  • @Html.DisplayForModel("TestClientReferences")
添加后Api.cshtml文件的代码如下
  1. @using System.Web.Http
  2. @using WebApiDemo.Areas.HelpPage.Models
  3. @model HelpPageApiModel
  4. @{
  5.     var description = Model.ApiDescription;
  6.     ViewBag.Title = description.HttpMethod.Method + " " + description.RelativePath;
  7. }
  8. <link type="text/css" href="~/Areas/HelpPage/HelpPage.css" rel="stylesheet" />
  9. <div id="body" class="help-page">
  10.     <section class="featured">
  11.         <div class="content-wrapper">
  12.             <p>
  13.                 @Html.ActionLink("Help Page Home", "Index")
  14.             </p>
  15.         </div>
  16.     </section>
  17.     <section class="content-wrapper main-content clear-fix">
  18.         @Html.DisplayForModel()
  19.     </section>
  20. </div>
  21. @Html.DisplayForModel("TestClientDialogs")
  22. @section Scripts{
  23.     <link href="~/Areas/HelpPage/HelpPage.css" rel="stylesheet" />
  24.     @Html.DisplayForModel("TestClientReferences")
  25. }
复制代码
 
2、设置读取注释的xml路径

其实,通过上面的步骤,我们的项目已经可以跑起来了,也可以调用接口测试。但是,还不能读取 /// <summary> 注释内里的东西。需要做如下设置才行。
(1)设置生成xml的路径。我们在项目上面点右键→属性→生成标签页设置xml的路径

(2)在xml的读取路径:在下图的HelpPageConfig.cs内里设置一句话,指定xml的读取路径。

这句代码如下:
  1. config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/WebApiDemo.xml")));
复制代码
 HelpPageConfig.cs完整文件入下:
  1. // Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData
  2. // package to your project.
  3. #define Handle_PageResultOfT
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.Diagnostics.CodeAnalysis;
  9. using System.Linq;
  10. using System.Net.Http.Headers;
  11. using System.Reflection;
  12. using System.Web;
  13. using System.Web.Http;
  14. #if Handle_PageResultOfT
  15. using System.Web.Http.OData;
  16. #endif
  17. namespace WebApiDemo.Areas.HelpPage
  18. {
  19.     /// <summary>
  20.     /// Use this class to customize the Help Page.
  21.     /// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
  22.     /// or you can provide the samples for the requests/responses.
  23.     /// </summary>
  24.     public static class HelpPageConfig
  25.     {
  26.         [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
  27.             MessageId = "WebApiDemo.Areas.HelpPage.TextSample.#ctor(System.String)",
  28.             Justification = "End users may choose to merge this string with existing localized resources.")]
  29.         [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
  30.             MessageId = "bsonspec",
  31.             Justification = "Part of a URI.")]
  32.         public static void Register(HttpConfiguration config)
  33.         {
  34.              Uncomment the following to use the documentation from XML documentation file.
  35.             //config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
  36.              Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
  37.              Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
  38.              formats by the available formatters.
  39.             //config.SetSampleObjects(new Dictionary<Type, object>
  40.             //{
  41.             //    {typeof(string), "sample string"},
  42.             //    {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
  43.             //});
  44.             // Extend the following to provide factories for types not handled automatically (those lacking parameterless
  45.             // constructors) or for which you prefer to use non-default property values. Line below provides a fallback
  46.             // since automatic handling will fail and GeneratePageResult handles only a single type.
  47. #if Handle_PageResultOfT
  48.             config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
  49. #endif
  50.             // Extend the following to use a preset object directly as the sample for all actions that support a media
  51.             // type, regardless of the body parameter or return type. The lines below avoid display of binary content.
  52.             // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
  53.             config.SetSampleForMediaType(
  54.                 new TextSample("Binary JSON content. See http://bsonspec.org for details."),
  55.                 new MediaTypeHeaderValue("application/bson"));
  56.              Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
  57.              and have IEnumerable<string> as the body parameter or return type.
  58.             //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));
  59.              Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
  60.              and action named "Put".
  61.             //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");
  62.              Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
  63.              on the controller named "Values" and action named "Get" with parameter "id".
  64.             //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");
  65.              Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
  66.              The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
  67.             //config.SetActualRequestType(typeof(string), "Values", "Get");
  68.              Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
  69.              The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
  70.             //config.SetActualResponseType(typeof(string), "Values", "Post");
  71.             config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/WebApiDemo.xml")));
  72.         }
  73. #if Handle_PageResultOfT
  74.         private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
  75.         {
  76.             if (type.IsGenericType)
  77.             {
  78.                 Type openGenericType = type.GetGenericTypeDefinition();
  79.                 if (openGenericType == typeof(PageResult<>))
  80.                 {
  81.                     // Get the T in PageResult<T>
  82.                     Type[] typeParameters = type.GetGenericArguments();
  83.                     Debug.Assert(typeParameters.Length == 1);
  84.                     // Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
  85.                     Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
  86.                     object items = sampleGenerator.GetSampleObject(itemsType);
  87.                     // Fill in the other information needed to invoke the PageResult<T> constuctor
  88.                     Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
  89.                     object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };
  90.                     // Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
  91.                     ConstructorInfo constructor = type.GetConstructor(parameterTypes);
  92.                     return constructor.Invoke(parameters);
  93.                 }
  94.             }
  95.             return null;
  96.         }
  97. #endif
  98.     }
  99. }
复制代码
3、测试接口

下面仅为简朴接口,仅为项目说明利用
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Web.Http;
  7. namespace WebApiDemo.Controllers
  8. {
  9.     public class ValuesController : ApiController
  10.     {
  11.         // GET api/values
  12.         public IEnumerable<string> Get()
  13.         {
  14.             return new string[] { "value1", "value2" };
  15.         }
  16.         // GET api/values/5
  17.         public string Get(int id)
  18.         {
  19.             return "value";
  20.         }
  21.         // POST api/values
  22.         public void Post([FromBody]string value)
  23.         {
  24.         }
  25.         // PUT api/values/5
  26.         public void Put(int id, [FromBody]string value)
  27.         {
  28.         }
  29.         // DELETE api/values/5
  30.         public void Delete(int id)
  31.         {
  32.         }
  33.     }
  34. }
复制代码
         到这里组件就搭完了,剩下的就是运行了。如果过我们是是把webAPI摆设在IIS或其他服务器上,在浏览器url内里敲地址http://IP地址:端口/Help即可显示WebApiTestClient调试页面;这里我是直接通过Visual Studio 2017调试弹出WebApiTestClient调试页面,如下:
WebApiTestClient调试页面展示:

接口调试:
点击某一个接口检察接口具体。例如本文检察Get哀求的无参方法,右下角有按钮可以测试接口。 


点击“Test API”按钮

点击Send发送哀求
 
第二个有参数的接口


手动输入参数
 点“Send”得到返回结果

 
四、总结

        WebApiTestClient 是一种专门用于调试和测试 ASP.NET WebApi 的工具,其设计简洁、功能强大,具有以下几大优点:
1. 简洁易用


  • Web界面:无需安装繁琐的外部工具,通过浏览器即可访问和利用,界面友爱,操作简朴。
  • 易于集成:作为 NuGet 包,可以方便地集成到现有的 ASP.NET WebApi 项目中,设置简朴,不需要额外的复杂步骤。
2. 机动的哀求设置


  • 多种HTTP方法:支持 GET、POST、PUT、DELETE 等常见的 HTTP 哀求方法,能够模拟各种哀求场景。
  • 自界说哀求参数:允许用户自界说哀求头、哀求体和查询参数,机动性高,便于模拟现实应用中的复杂哀求。
3. 实时检察相应


  • 即时反馈:可以即时检察 API 的相应结果,包罗状态码、相应头和相应体,帮助开发者快速发现和定位标题。
  • 具体信息:能够具体显示哀求和相应的所有细节,便于调试和分析。
4. 提高开发服从


  • 快速验证:在开发过程中,可以快速验证 API 的功能是否精确,无需切换到其他工具,大大提高开发服从。
  • 减少联调时间:前后端分离的开发模式下,前端开发人员可以快速验证后端 API 的接口,减少前后端联调的时间和成本。
5. 便于展示和沟通


  • 演示友爱:在需求评审或技术交换过程中,可以利用 WebApiTestClient 进行实时演示,展示 API 的功能和数据交互过程,提高沟通服从。
  • 文档生成:部分集成了API文档生成功能,便于开发者和测试人员检察和利用。
6. 设置机动


  • 路由设置:可以机动设置路由,适应不同项目的需求。
  • 环境适应:实用于开发、测试环境,便于不同阶段的调试和测试工作。
7. 无需依赖外部工具


  • 内置办理方案:作为 ASP.NET WebApi 的内置调试办理方案,不需要依赖外部工具,减少了环境设置和维护的复杂度。
          WebApiTestClient 以其简洁易用、机动设置、即时反馈等优点,成为了调试和测试 ASP.NET WebApi 的抱负工具。它不但提高了开发和测试服从,而且在前后端联调、需求评审等场景中也发挥了重要作用,为开发者提供了极大的便利。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

曹旭辉

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表