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#.
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:
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:
- public static string AddNewPet
- {
- get
- {
- return $"{CustomConfigurationProvider.GetKey("petStoreService-baseUrl")}" + "pet";
- }
- }
"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:
As mentioned, the above request URL has been created. Now let's add the test data to create a pet in the .json file.
- "Add new PET": {
- "id": 121,
- "category": {
- "id": 2,
- "name": "Sheen"
- },
- "name": "doggie",
- "photoUrls": [
- "string"
- ],
- "tags": [
- {
- "id": 0,
- "name": "string"
- }
- ],
- "status": "available"
- }
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.
- public CreatePet_Response Validate_AddPet(CreatePet_Request createPetRequest) {
-
- RestClient restClient = new RestClient();
- RestRequest restRequest = new RestRequest(Method.POST);
- IRestResponse restResponse;
-
-
- restClient.BaseUrl = new Uri(PetStoreAPIMethods.AddNewPet);
-
- var request = JsonConvert.SerializeObject(createPetRequest.createPetRequestObjectProperty);
- restRequest.AddJsonBody(request);
-
-
- restResponse = restClient.Execute(restRequest);
-
-
- if (restResponse.StatusCode == System.Net.HttpStatusCode.OK) {
-
- return JsonConvert.DeserializeObject < CreatePet_Response > (restResponse.Content);
- } else {
- LoggerOutput.WriteLine("Not a valid input" + restResponse.StatusCode);
- return null;
- }
-
- }
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
- public void ValidateCreatePetHasAdded(object jsonInput) {
- var data = JObject.Parse(jsonInput.ToString());
- var requests = new CreatePet_Request();
- CreatePet_RequestObject objectRequest = new CreatePet_RequestObject();
- objectRequest = JsonConvert.DeserializeObject < CreatePet_RequestObject > (jsonInput.ToString());
- objectRequest.id = int.Parse(data["id"].ToString());
- objectRequest.name = data["name"].ToString();
-
-
- Category category = new Category();
- category.id = int.Parse(data["category"]["id"].ToString());
- category.name = data["category"]["name"].ToString();
-
- objectRequest.category = category;
-
- for (int i = 0; i < objectRequest.photoUrls.Count; i++) {
- var photeUrls = objectRequest.photoUrls[i].ToString();
- }
- for (int i = 0; i < objectRequest.tags.Count; i++) {
- var tagID = objectRequest.tags[i].id.ToString();
- var tagName = objectRequest.tags[i].name.ToString();
- }
-
- objectRequest.status = data["status"].ToString();
-
-
- requests.createPetRequestObjectProperty = objectRequest;
-
-
- var responseObject = new PetStoreAPIActions(LoggerOutput).Validate_AddPet(requests);
- if (responseObject != null) {
-
- Assert.True(responseObject.Id == objectRequest.id, "Id is matching");
- Assert.True(responseObject.Name == objectRequest.name, "Name is matching");
- Assert.True(responseObject.Status == objectRequest.status, "status is matching");
-
- for (int i = 0; i < responseObject.Tags.Length; i++) {
- Assert.True(responseObject.Tags[i].id == objectRequest.tags[i].id, "Tag ID is matching");
- Assert.True(responseObject.Tags[i].name == objectRequest.tags[i].name, "tag Name is matching");
- }
-
- for (int i = 0; i < responseObject.PhotoUrls.Length; i++) {
- Assert.True(responseObject.PhotoUrls[i].ToString() == objectRequest.photoUrls[i].ToString(), "Photo urls is matching");
- }
- }
- }
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.
- public class PetStoreTests {
- private readonly ITestOutputHelper output;
-
- public PetStoreTests(ITestOutputHelper output) {
- this.output = output;
- }
-
- [Fact]
- [Trait("Category", "petStore")]
- public void CreatePet_PostMethod() {
- new ServiceWorkFlow(output).ValidateCreatePetHasAdded(CustomConfigurationProvider.GetSection($ "AddPETAPI"));
- }
- }
Run the abve test cases in Test Explorer,
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.
Let's see the code for the get method in an API action class.
- public string Get_PetDetails_ByPetID(string id) {
-
- RestClient restClient = new RestClient();
- RestRequest restRequest = new RestRequest(Method.POST);
- IRestResponse restResponse;
-
-
- var url = PetStoreAPIMethods.GetPetByID.Replace("{id}", id);
- restClient.BaseUrl = new Uri(url);
- restResponse = restClient.Execute(restRequest);
-
-
- if (restResponse.StatusCode == System.Net.HttpStatusCode.OK) {
-
- return "Pet has been created";
- } else
- return null;
- }
Now let us see the serviceWorkflow methods and Tests
- public bool Validate_GetPetResponse(string id, object jsonInput) {
- var data = JObject.Parse(jsonInput.ToString());
- var response = new PetStoreAPIActions(LoggerOutput).Get_PetDetails_ByPetID(id);
-
- if (response.Equals("Pet has been created"))
- return true;
- else
- return false;
- }
- [Fact]
- [Trait("Category", "petStore")]
- public void Validate_GetPetById()
- {
- var result = new ServiceWorkFlow(output).Validate_GetPetResponse(CustomConfigurationProvider.GetSection($"AddPETAPI.id"), CustomConfigurationProvider.GetSection($"AddPETAPI"));
- if (!result)
- output.WriteLine("Pet Has not been created"+ result);
- else
- output.WriteLine("Pet has been created");
- }
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 :-)