简体   繁体   English

如何获取API响应状态或状态代码

[英]How to get an API response status or Status code

Im learning c#, VS in combination with RestSharp and SpecFlow to try and learn some Automated API testing and im am trying to get the either the response code, or the response status in order to verify the either of the two using an Assert statement. 我正在学习c#,VS以及RestSharp和SpecFlow,以尝试学习一些自动化的API测试,并且正在尝试获取响应代码或响应状态,以便使用Assert语句来验证二者之一。

The problem i'm having is that i cant seem to get the response and display it as a response code. 我遇到的问题是我似乎无法获得响应并将其显示为响应代码。 ie 200 or as a response status int String format. 即200或作为响应状态int字符串格式。 ie "OK" 即“确定”

I've written the following code with a print statement that should print the response code but when i run the code i get a empty line printed in the output. 我用打印语句编写了以下代码,该语句应打印响应代码,但是当我运行代码时,输​​出中会打印出空行。

using System;
using System.Net;
using TechTalk.SpecFlow;
using RestSharp;
using NUnit.Framework;

namespace SWAPITEST.Steps
{
[Binding]
public class SWAPIFeaturesSteps : BaseSteps
{
    //private RestClient restClient;
    //private RestRequest restRequest;
   // private IRestResponse restResponse;

    [Given(@"i sen an api request for a luke skywalker")]
    public void GivenISenAnApiRequestForALukeSkywalker()
    {
     restRequest = new RestRequest(Method.GET);

    }

    [When(@"the response code is received")]
    public void WhenTheResponseCodeIsReceived()
    {
        restResponse = restClient.Execute(restRequest);
    }

    [Then(@"the Resonse code is OK")]
    public void ThenTheResonseCodeIsOK()
    {
        HttpStatusCode statusCode = restResponse.StatusCode;
        int numericStatusCode = (int)statusCode;
        Console.WriteLine(numericStatusCode);
    }
}
}

This prints a code 0 which suggests the call is being terminated, however if i send the same call using postman i receive an ok response status 200 这将打印一个代码0,表明该呼叫已终止,但是,如果我使用邮递员发送了相同的呼叫,则会收到一个好的响应状态200

BaseSteps class BaseSteps类

public class BaseSteps
{
    protected RestClient restClient;
    protected RestRequest restRequest;
    protected IRestResponse restResponse;

    protected readonly Uri BaseUri = new Uri("http://swapi.co/api/people/1");
    public BaseSteps()
    {
        restClient = new RestClient();


    }

Can anyone tell me how i can get the response code and use it in an assert? 谁能告诉我如何获取响应代码并在断言中使用它? for example: 例如:

Assert.That(resp.ToString, Is.EqualTo(200));

or how i could assert on the actual status of the response? 或者我如何断言响应的实际状态? for example: 例如:

Assert.That(resp.ToString, Is.EqualTo("OK"));

I don't use RestSharp but this is what I would think you need to do to create a request that knows where to make the request: 我不使用RestSharp,但这是我认为您需要执行的操作,以创建知道在哪里发出请求的请求:

[Given(@"i sen an api request for a luke skywalker")]
public void GivenISenAnApiRequestForALukeSkywalker()
{
 restRequest = new RestRequest(BaseUri.AbsoluteUri, Method.GET);

}

This is an old thread but this is an answer for anyone that finds this. 这是一个旧线程,但这是找到它的任何人的答案。

Your steps don't know about each other. 您的步骤彼此不了解。 The response is being set in the When but isn't being stored anywhere for use in your Then where you are trying to get the response code from. 响应是在“何时”设置的,但没有存储在“然后”中的任何位置,您试图从中获取响应代码。 You can store the response in a Scenario Context and pull it back in your future step. 您可以将响应存储在方案上下文中,并在以后的步骤中将其拉回。

Store It ScenarioContext.Current.Add("response", response); 存储它ScenarioContext.Current.Add("response", response); Where the first argument is the key and the second is the actual response. 其中第一个参数是键,第二个参数是实际响应。

Retrieve It var response = ScenarioContext.Current["response"]; 检索它var response = ScenarioContext.Current["response"];

Now if you cast the response code to an int you will get the numeric code. 现在,如果将响应代码转换为整数,则将获得数字代码。 (int)response.StatusCode since you have the populated response in your Then step. (int)response.StatusCode因为您在“然后”步骤中已填充了响应。

Update***** 7/15/2019 更新***** 7/15/2019

The Scenario Context is being phased out in favor of Context Injection. 场景上下文正在逐步淘汰,而有利于上下文注入。 To get this same functionality I did the following: Created a Class that holds a Dictionary the context entries are added to. 为了获得相同的功能,我执行了以下操作:创建一个包含词典的类,将上下文条目添加到其中。 It is of type <string, object> which allows me to insert pretty much anything into it. 它的类型为<string, object> ,它使我可以在其中插入几乎所有内容。

using System;
using System.Collections.Generic;

namespace CentralFramework.ScenarioContext
{
    public class ContextEntries
    {
        public Dictionary<string, object> contextCollection = new Dictionary<string, object>();
    }
}

Then in any class that I want to use it in I add the following: 然后在任何我想使用它的类中添加以下内容:

public class ScenarioHooks //An example class 
{
    ContextEntries context;

    public ScenarioHooks(ContextEntries context) //Newing up an instance in the constructor
    {
        this.context = context;
    }

To store something in the context it is very much like the original answer: 在上下文中存储内容非常类似于原始答案:

context.contextCollection.Add("webDriver", webDriver);//Adding the webdriver to the collection, It could be anything.

To retrieve something from the collection: 要从集合中检索内容:

IWebDriver webDriver = (IWebDriver)context.contextCollection["webDriver"]; 

Just like with the Scenario Context you need to make sure you set the type when retrieving with the () since it is just stored as an object (string), (int), etc... 就像场景上下文一样,您需要确保在使用()检索时设置类型,因为它只是存储为对象(字符串),(int)等。

To remove something from the collection: 要从集合中删除内容:

context.contextCollection.Remove("webDriver");

All of the above examples are just how you deal with a dictionary. 以上所有示例都是您如何处理字典的方法。 There is nothing special there. 那里没有什么特别的。 This solution works well. 此解决方案效果很好。 It has all of the validation that comes with a standard dictionary also which is nice. 它具有标准字典附带的所有验证,这也很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM