API - Automation Using Xunit

Introduction 

 
Hello friends, today I am going to explain how to create an XUnit framework and how to automate Swagger endpoints by taking the online available swagger endpoint.
 
Let's get started. First, we need Visual Studio 2019, 2017. In this article, I am creating the Xunit framework in VisualStudio 2019. 
 
About xunit - https://xunit.net/docs/why-did-we-build-xunit-1.0
 
Open the VS2019 and Create Xunitframework using c#.
 
API - Automation Using Xunit
 
API - Automation Using Xunit
 
API - Automation Using Xunit
 
Create a Project and Create the folders inside the project as shown in above screenshots.
 
Now let's add the necessary Nuget packages. Please add the necessary packages as mentioned in the screenshot below:
 
API - Automation Using Xunit
 
Add the above Nuget Packages and "PetStoreTestData.json" file.
 
The next step is to create Request urls in "Helpers" folder. Please add "PetStoreAPIMethods.cs" file. Add the request URLs as mentioned below:
  1. public static string AddNewPet  
  2. {  
  3.     get  
  4.     {  
  5.         return $"{CustomConfigurationProvider.GetKey("petStoreService-baseUrl")}" + "pet";  
  6.     }  
  7. }  
"petStoreService-baseUrl" is nothing but the swagger URL: https://petstore.swagger.io/. The appended string "pet is the end point name. Below is the swagger end point:
 
API - Automation Using Xunit
 
As mentioned, the above request URL has been created. Now let's add the test data to create a pet in the .json file.
  1. "Add new PET": {      
  2.      "id": 121,  
  3.      "category": {  
  4.        "id": 2,  
  5.        "name""Sheen"  
  6.      },  
  7.      "name""doggie",  
  8.      "photoUrls": [  
  9.        "string"  
  10.      ],  
  11.      "tags": [  
  12.        {  
  13.          "id": 0,  
  14.          "name""string"  
  15.        }  
  16.      ],  
  17.      "status""available"  
  18.    }  
After adding the test data, we need to create a "Post method" API in our Pet store automation project. Since we have used the REST Client. We need to write a code to fetch the base URL and execute the post method like this.
 
Action methods need to be written in "Action class" so we need to create  "PetStoreAPIActions.cs" in "Helpers" folder
 
Post Method for adding a pet.
  1. public CreatePet_Response Validate_AddPet(CreatePet_Request createPetRequest) {  
  2.  //Creating a RestClient    
  3.  RestClient restClient = new RestClient();  
  4.  RestRequest restRequest = new RestRequest(Method.POST); // Since this is a post method Method.post    
  5.  IRestResponse restResponse;  
  6.   
  7.  //We need to create request base url    
  8.  restClient.BaseUrl = new Uri(PetStoreAPIMethods.AddNewPet);  
  9.  //serializing and sending the data    
  10.  var request = JsonConvert.SerializeObject(createPetRequest.createPetRequestObjectProperty);  
  11.  restRequest.AddJsonBody(request);  
  12.   
  13.  //now execute the above request    
  14.  restResponse = restClient.Execute(restRequest);  
  15.  //Now validate the staus of the response    
  16.   
  17.  if (restResponse.StatusCode == System.Net.HttpStatusCode.OK) {  
  18.   //Deserialize the response from json and return the response object    
  19.   return JsonConvert.DeserializeObject < CreatePet_Response > (restResponse.Content);  
  20.  } else {  
  21.   LoggerOutput.WriteLine("Not a valid input" + restResponse.StatusCode);  
  22.   return null;  
  23.  }  
  24.   
  25. }  
After executing the above method, we need to compare whether the testdata we have passed has been stored or not. So, we need to create a service workflow and verify the response of the "pet" endpoint
 
ServiceWorkflow.cs code
  1. public void ValidateCreatePetHasAdded(object jsonInput) {  
  2.  var data = JObject.Parse(jsonInput.ToString()); // parsing the json in to request object property    
  3.  var requests = new CreatePet_Request();  
  4.  CreatePet_RequestObject objectRequest = new CreatePet_RequestObject();  
  5.  objectRequest = JsonConvert.DeserializeObject < CreatePet_RequestObject > (jsonInput.ToString());  
  6.  objectRequest.id = int.Parse(data["id"].ToString()); // since id is in Integer we need to parse json string to integer    
  7.  objectRequest.name = data["name"].ToString();  
  8.   
  9.  //To add Category. Category is of object type so we need to add them like this    
  10.  Category category = new Category();  
  11.  category.id = int.Parse(data["category"]["id"].ToString());  
  12.  category.name = data["category"]["name"].ToString();  
  13.   
  14.  objectRequest.category = category;  
  15.  //Photo urls is of type array    
  16.  for (int i = 0; i < objectRequest.photoUrls.Count; i++) {  
  17.   var photeUrls = objectRequest.photoUrls[i].ToString();  
  18.  }  
  19.  for (int i = 0; i < objectRequest.tags.Count; i++) {  
  20.   var tagID = objectRequest.tags[i].id.ToString();  
  21.   var tagName = objectRequest.tags[i].name.ToString();  
  22.  }  
  23.   
  24.  objectRequest.status = data["status"].ToString();  
  25.   
  26.  //Assigning all the data from objectRequest to request object property    
  27.  requests.createPetRequestObjectProperty = objectRequest;  
  28.   
  29.  //send the request to API post method to execute and get the response back from the request API    
  30.  var responseObject = new PetStoreAPIActions(LoggerOutput).Validate_AddPet(requests);  
  31.  if (responseObject != null) {  
  32.   //Validate response data    
  33.   Assert.True(responseObject.Id == objectRequest.id, "Id is matching");  
  34.   Assert.True(responseObject.Name == objectRequest.name, "Name is matching");  
  35.   Assert.True(responseObject.Status == objectRequest.status, "status is matching");  
  36.   //Tags response comparision    
  37.   for (int i = 0; i < responseObject.Tags.Length; i++) {  
  38.    Assert.True(responseObject.Tags[i].id == objectRequest.tags[i].id, "Tag ID is matching");  
  39.    Assert.True(responseObject.Tags[i].name == objectRequest.tags[i].name, "tag Name is matching");  
  40.   }  
  41.   //photourls    
  42.   for (int i = 0; i < responseObject.PhotoUrls.Length; i++) {  
  43.    Assert.True(responseObject.PhotoUrls[i].ToString() == objectRequest.photoUrls[i].ToString(), "Photo urls is matching");  
  44.   }  
  45.  }  
  46. } 
Now the final step is to write the test cases. For that, we need to create tests.cs file in the "Tests" folder. Try to run the above test case using XUnit.
  1. public class PetStoreTests {  
  2.  private readonly ITestOutputHelper output;  
  3.   
  4.  public PetStoreTests(ITestOutputHelper output) {  
  5.   this.output = output;  
  6.  }  
  7.   
  8.  [Fact]  
  9.  [Trait("Category""petStore")]  
  10.  public void CreatePet_PostMethod() {  
  11.   new ServiceWorkFlow(output).ValidateCreatePetHasAdded(CustomConfigurationProvider.GetSection($ "AddPETAPI"));  
  12.  }  
  13. } 
Run the abve test cases in Test Explorer,
 
API - Automation Using Xunit
 
Get Method API
 
In the above test case, we have added the PET using Post. Let us now automate the GET method and verify we can able to fetch the pet we added in the POST method.
 
Here, I am validating the status code. If we pass the pet Id, what we added in the POST method, our response code will be a success.
 
API - Automation Using Xunit
 
Let's see the code for the get method in an API action class.
  1. public string Get_PetDetails_ByPetID(string id) {  
  2.  //Creating a RestClient    
  3.  RestClient restClient = new RestClient();  
  4.  RestRequest restRequest = new RestRequest(Method.POST); // Since this is a post method Method.post    
  5.  IRestResponse restResponse;  
  6.   
  7.  //We need to create request base url, we need to pass pet id here    
  8.  var url = PetStoreAPIMethods.GetPetByID.Replace("{id}", id);  
  9.  restClient.BaseUrl = new Uri(url);  
  10.  restResponse = restClient.Execute(restRequest);  
  11.   
  12.  //Validate the response    
  13.  if (restResponse.StatusCode == System.Net.HttpStatusCode.OK) {  
  14.   //Returning the request object, When we execute the Get method we get Pet Created response.    
  15.   return "Pet has been created";  
  16.  } else  
  17.   return null;  
  18. }   
Now let us see the serviceWorkflow methods and Tests
  1. public bool Validate_GetPetResponse(string id, object jsonInput) {  
  2.  var data = JObject.Parse(jsonInput.ToString());  
  3.  var response = new PetStoreAPIActions(LoggerOutput).Get_PetDetails_ByPetID(id);  
  4.   
  5.  if (response.Equals("Pet has been created"))  
  6.   return true;  
  7.  else  
  8.   return false;  
  9. } 
  1. [Fact]  
  2. [Trait("Category""petStore")]  
  3. public void Validate_GetPetById()  
  4. {  
  5.     var result = new ServiceWorkFlow(output).Validate_GetPetResponse(CustomConfigurationProvider.GetSection($"AddPETAPI.id"), CustomConfigurationProvider.GetSection($"AddPETAPI"));
  6.     if (!result)  
  7.         output.WriteLine("Pet Has not been created"+ result);  
  8.     else  
  9.         output.WriteLine("Pet has been created");  
  10. }  
API - Automation Using Xunit
 
This is how you can automate Swagger endpoints in API automation. I am uploading the project for your reference. The rest of the API methods in swagger I haven't automated. I want you guys to try it! Let me know if you have any doubts understanding this framework, and if so, please comment below. Surely, I will reply to you.
 
I hope you enjoyed this article :-)