About a year ago I was worked on a project where we had to write a RESTful API from the ground up in Node. After the first few controllers, manual testing become quite tedious and labor intensive. One of the biggest rules in SQA is “automate what you can”. So, once we had a few endpoints solidified to match the RESTful pattern, I got to work. It took about 8 hours to come up with this automated testing solution and it saved countless hours of manual QA and tickets bouncing back-and-forth between QA and DEV (because they didn’t have unit tests). I put the solution on a VM that anyone working on the project could access, modify, and run. Let’s get started with API Testing Using Powershell.
I wanted to use the HttpClient from .Net 4.5 that I used in a lot of previous projects. The devs I was working with were MEAN and LAMP stack proficient, so I had to be sure to “Keep It Stupid Simple” and be sure to comment.
As previously mentioned, I use the HttpClient (System.Net.Http.dll). I also import the JSON.Net (Newtonsoft.Json.dll) library to parse the JSON response from the RESTful API. In the project you’ll also see a .CSV file (check it out on GitHub). The CSV file is what makes this a data-driven testing solution that is easily updated and read by both machine and man.
You can view/fork the code from my GitHub project. You’ll need Powershell to run it, but I highly recommend using Powershell ISE. I am not going to copy+paste the code like in my other posts but rather I will explain it at a high-level.
What’s Going On
- Get the Present Working Directory (pwd) and save it for the next few steps
- Import the .dll files (see “The Setup” above)
- Set the BaseUrl, so that only the endpoints need to be specified in the .CSV file
- This allows you to easily switch environments
- Create a new instance of the HttpClient
- This will hold your session, so that you can log-in with one test and then do some call that requires a valid session afterwards
- Import the .CSV file
- Parse the .CSV file using a foreach loop
- Create an error array
- Create a description of the current test (row of the .CSV)
- Build a request with the given data
- If the Method is PUT or POST, then add the body content
- Send the request and save the response
- Save the response’s status code
- Save the response’s content
- If the expected status code does not match the response’s, then we add that error message to the error array
- If the error array has any length, then we print out an error (with red text-color)
- Else, print out a success message (with green-text)
- If there is a comment in the .CSV file’s current row, then print that out (with gray-text)
API Testing Using Powershell in Action