我需要一些关于Visual Studio上的WebTestRequest的帮助
我有2个请求,第二个请求需要第一个请求响应中的一些数据
如何使用第一次响应第二次请求时需要的特定数据? (在我的情况下是Sessionid
)
测试请求:
{
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TestTools.WebTesting;
public class WebTest1Coded : WebTest
{
public WebTest1Coded()
{
this.PreAuthenticate = true;
this.Proxy = "default";
}
public override IEnumerator<WebTestRequest> GetRequestEnumerator()
{
WebTestRequest request1 = new WebTestRequest("https://xxx.xxx.com/api/xxx");
request1.Method = "POST";
request1.QueryStringParameters.Add("format", "json", false, false);
StringHttpBody request1Body = new StringHttpBody();
request1Body.ContentType = "application/json";
request1Body.InsertByteOrderMark = false;
request1Body.BodyString = "{\"UserName\":\"xxx\",\"Password\":\"xxx\"}";
request1.Body = request1Body;
yield return request1;
request1 = null;
WebTestRequest request2 = new WebTestRequest("https://xxx.xxx.com/api/xxx");
request2.Method = "POST";
request2.QueryStringParameters.Add("format", "json", false, false);
StringHttpBody request2Body = new StringHttpBody();
request2Body.ContentType = "application/json";
request2Body.InsertByteOrderMark = false;
request2Body.BodyString = @"
RequestHeader"":
""SessionId"""": ""xxx"",
""ApiKey"""": ""xxx""
request2.Body = request2Body;
yield return request2;
request2 = null;
}
}
答案 0 :(得分:0)
在原始Web测试文件中比在编码Web测试中更容易。只需在第一个请求中添加提取规则即可。它将值保存到上下文参数中,然后可以在第二个请求中使用。
如果您确实想使用Coded Web Test,那么您可以使用合适的提取规则和上下文参数用法创建沙盒Web测试。然后将其转换为Coded并将有趣的位复制到测试中。
ExtractText
规则,用于在abc
和def
之间提取文本,并将结果存储在生成以下代码的acbdef
上下文参数中。
WebTestRequest request3 = new WebTestRequest("http://localhost/");
request3.ThinkTime = 1;
request3.ParseDependentRequests = false;
ExtractText extractionRule1 = new ExtractText();
extractionRule1.StartsWith = "abc";
extractionRule1.EndsWith = "def";
extractionRule1.IgnoreCase = false;
extractionRule1.UseRegularExpression = false;
extractionRule1.Required = true;
extractionRule1.ExtractRandomMatch = false;
extractionRule1.Index = 0;
extractionRule1.HtmlDecode = true;
extractionRule1.SearchInHeaders = false;
extractionRule1.ContextParameterName = "abcdef";
request3.ExtractValues += new EventHandler<ExtractionEventArgs>(extractionRule1.Extract);
yield return request3;
request3 = null;
其他提取规则具有需要赋予值的不同属性。我建议将您想要的主要细节放入Web测试,然后执行生成代码以确切了解C#代码的必要性。
提取的值在下一个请求中的三个位置使用:
WebTestRequest request4 = new WebTestRequest(
("http://localhost/" + (this.Context["abcdef"].ToString() + "/more")));
request4.ThinkTime = 1;
request4.ParseDependentRequests = false;
request4.Headers.Add(new WebTestRequestHeader("Use-abcdef-again",
("pqr" + (this.Context["abcdef"].ToString() + "stu"))));
request4.Headers.Add(new WebTestRequestHeader("Use-abcdef",
this.Context["abcdef"].ToString()));
yield return request4;
request4 = null;