简体   繁体   中英

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.

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. 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

BaseSteps class

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:

[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); Where the first argument is the key and the second is the actual response.

Retrieve It 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.

Update***** 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.

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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