Use Approval Tests with Swagger to ensure your API
Today I read this tweet from Joseph Woodward in which he explains how to use the approval test methodology to ensure the constraints of our API in order to avoid fatal errors like changes in DTO properties or return new types of responses. I really enjoy this approach so much that I like to fork it to Java (here), you can take a look to original here in C#, and try to implement it by myself.
The application is a simple Spring Boot application with Swagger made with the starter web, with the following main parts:
Controller
Model
At this point if you launch the server and visit the endpoint you should see the following JSON:
And here the swagger UI:
Tests
Now that we have our API working we can start with the tests, first of all you need to install the Approval Test library and configure the test class as following:
Now you can run the test, the first time you pass the test it should fail and the library should created two files :
- TestingApplicationTests.DocumentHasChanged.received.txt with the content of the Swagger JSON file and
- TestingApplicationTests.DocumentHasChanged.approved.txt with no content.
You should copy the content of the received file to the approved file, save and pass the test again, now with success!
At this point you have the current Swagger document which defines your API and any change will make the test fails, like for example change one property name in our model.
If you run the test again, this time it should fails.