SpringBoot: Generate OpenAPI Document During Test Phase

George Berar
2 min readApr 19, 2022

--

In today’s article I will show you how to generate the OpenAPI document containing the API definitions during test phase.

Image credits to ZEGETECH

Before we start you can find the entire code here.

What We Build?

An integration test which generates the OpenAPI document containing the definitions for a simple REST API which is documented using the Springdoc library.

Why We Build?

To better keep track of our API changes and automate the process in order to exclude the manual intervention of a developer to update the docs manually because is error prone.

How We Build?

Maven Dependencies

Add the Springdoc dependency in your pom.xml:

Other versions here.

Configure the spring-boot-starter-test dependency in order to use JUnit5:

Define The API

The business logic behind it does not matter as we are more interested to document it correctly using the Springdoc annotations.

Notice the @Tag, @Operation, @ApiResponses and @Parameter annotations which are used to document the API. All of them are part of the io.swagger.v3.oas.annotations package.

Write The Integration Test

Note: make sure you import the correct test annotations from org.junit.jupiter.api package.

The purpose of this integration test is to spin up the Spring context and request the /v3/api-docs.yaml endpoint in order to get the generated API definitions and write them to a separate file.

I’m using the MockMvc to execute the request. You can read about integration testing strategies here and here.

Configure Maven Surefire Plugin

I’m using the Maven Surefire plugin to run unit & integration tests with

mvn clean install or mvn test commands.

Run The Tests

In order to run the tests we use mvn clean install or mvn test commands. After the test phase is completed we can find a new file called openapi.yaml which was created by our integration test under src/main/resources/apidocs folder:

Note: if you want to generate the file somewhere else you need to modify the path in the integration test.

If you open the file you will see something like this:

Conclusion

As always please keep in mind this approach might or might not suit your project context or needs and I’m not in the position to say there’s no other way to do it differently or better. I really hope you enjoyed it and had fun reading it.

Stay safe and remember you can find the code here.

--

--

George Berar

Senior Software Engineer • Freelancer • Tech Enthusiast