Use Approval Tests with Swagger to ensure your API

Pedro López Mareque
3 min readAug 28, 2019

--

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

A REST Controller with one endpoint which returns a lists of products.

Model

Product model with two properties

At this point if you launch the server and visit the endpoint you should see the following JSON:

JSON response

And here the swagger UI:

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:

Test class

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.

Change Product property

If you run the test again, this time it should fails.

--

--