如何在 VS WebTest 中 post 一个 Json 对象?

How to post a Json object in a VS WebTest?

我正在 Visual Studio 2015 Enterprise 中编写一些网络测试,以对我的 API.

进行负载测试

我的几个 API 调用期望 Json 对象作为请求的主体。但是webtest界面好像没有办法直接设置Post请求体;您可以添加键和值,但不能将请求设置为隐式序列化的对象,甚至只是一个纯字符串。

那么您如何 post Json 进行网络测试?

根据您的需要,有两种选择,也许更多。这两种机制都具有相同的属性集来设置 URL 和许多其他字段。

在 Web 测试编辑器中,您可以添加 Web 服务请求(Insert web service request 上下文菜单命令),然后将其设置为 StringBody 字段。字符串主体的内容可以包含上下文参数。

普通请求的上下文菜单有一个 Add file upload parameter

搜索了一段时间后,我找到了一个解决方案,允许您在 Web 测试的 post 请求中通过 JSON 对象发送。

1) 创建一个网络测试性能插件:https://docs.microsoft.com/en-us/visualstudio/test/how-to-create-a-web-performance-test-plug-in?view=vs-2017

2) 在class中添加如下代码(别忘了build):

using System.ComponentModel;
using Microsoft.VisualStudio.TestTools.WebTesting;

namespace WebTests.RequestPlugins
{
    [DisplayName("Add JSON content to Body")]
    [Description("HEY! Tip! Uglify your JSON before pasting.")]
    public class AddJsonContentToBody : WebTestRequestPlugin
    {
        [Description("Assigns the HTTP Body payload to the content provided and sets the content type to application/json")]
        public string JsonContent { get; set; }

    public override void PreRequest(object sender, PreRequestEventArgs e)
    {
        var stringBody = new StringHttpBody();
        stringBody.BodyString = JsonContent;
        stringBody.ContentType = "application/json";

        e.Request.Body = stringBody;
    }
}

3) 根据您的要求 URL r-click 和 select 'Add Request Plugin' 然后您应该会看到您的新插件。

4) 丑化你的json以便能够粘贴。

5) 运行 测试

源代码:https://ericflemingblog.wordpress.com/2016/01/21/helpful-custom-request-plugins-for-web-tests/

在网络测试中 -> 字符串正文 -> 内容类型 属性,

  • 键入值 "application/json"
  • 将json添加到字符串主体

Content Type Picture for Json Data