【问题标题】:Request Body returns null in API automation testing in C# visual studio请求正文在 C# Visual Studio 的 API 自动化测试中返回 null
【发布时间】:2020-11-15 09:41:47
【问题描述】:

这是我的代码

        public static RestRequest CreateReportRequest()
        {            
            restRequest = new RestRequest(Method.POST);
            restRequest.AddHeader("Content-Type", "application/json");
            restRequest.AddHeader("Authorization", "Basic T1NUAxNFVxeTIwag==");
            using (StreamReader file = 
File.OpenText(@"C:\Automation\APIAutomationSuite\APIAutomationSuite\TestData\CreateReport.json"))
            using (JsonTextReader reader = new JsonTextReader(file))
            {
                JObject Body = (JObject)JToken.ReadFrom(reader);                    
            }            
            restRequest.AddJsonBody(Body);
            var response = client.Execute(restRequest);
            return restRequest;
        }

当我调试代码时,我在“JObject Body”中看到 json 请求正文值,但是当按 F10 并移动到下一条语句 (restRequest.AddJsonBody(Body);) 时,正文值变为空。这会引发错误的请求错误。 请帮我解决这个问题。

【问题讨论】:

  • 在 using 语句之外声明“JObject Body”。它可能会失去作用域

标签: c# visual-studio api automation


【解决方案1】:

您的Body 变量在using 语句的inner 范围内声明。因此,当您尝试在 using 之外引用它时 - 它是未声明的。

您可以将方法的末尾完全移动到using 范围内,我想这将消除您的问题。例如:

...
using (JsonTextReader reader = new JsonTextReader(file))
{
    JObject Body = (JObject)JToken.ReadFrom(reader);     
    restRequest.AddJsonBody(Body);
    var response = client.Execute(restRequest);
    return restRequest;               
}            

Understanding scope

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-02
    • 2019-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    相关资源
    最近更新 更多