0

I am new to C# and i am writing a test framework with Specflow,xunit and restsharp. My Step is as below

When I make a <ServiceName><Method> request
Then  I should get a success 200

Here as you can see the second step is common step which can be used in may features hence i am writing that in common step class. The challenge here is that how can i write a generic method for first and second step. In first a generic method to send request for any service and in second step to accept response from any service.

If i write just one method my code is like this

 RestClient restClient = new RestClient();
 RestRequest restRequest = new RestRequest(getUrl);
RestResponse<Root> result =  client.ExecuteGet<Root>(request);
        
  Debug.WriteLine($"response status code-{result.StatusCode}");
  Debug.WriteLine($"response status code-{result.Content}");

As i am writing a framework i want to set client at one class and use it everywhere and same with request and response. Also i am not able to share the context of test steps. I want any feature to access any step in solution. Please guide.

Greg Burghardt
  • 17,900
  • 9
  • 49
  • 92
amazo Tv
  • 3
  • 1

1 Answers1

0

Create a class for all request and below generic method inside.

       public class ApiReq
       {
        public ApiReq(string baseUrl)
        {
            _restClient= new RestClient();
            _restClient.BaseUrl = new Uri(baseUrl);
            _restClient.Timeout = 120000; //120 seconds
        }
        private T ExecuteMyRequest<T>(RestRequest request) where T : new()
        {
           //....
           
           var response = _restClient.Execute<T>(request);

           return response.Data;
        }
       }

use it in where you like;

     var baseUrl="http://localhost:3000";
     var request = new RestRequest("posts/{postid}", Method.Get);
     return new ApiReq(baseUrl).ExecuteMyRequest<YourClass>(request);
E S
  • 1
  • 1
  • 1