Sub topic 16
Testing the generated documentation
springdoc builds the OpenAPI document from your code at runtime. Annotations, properties and security rules all change that output, and a refactor can change it without any compile error. A renamed path, a lost @Operation, or an accidentally exposed endpoint will not fail your build. This chapter adds automated tests so those changes show up in CI.
You need the following: a Spring Boot 3 project with the springdoc starter, an OpenAPI bean, a documented BookController, JUnit 5 and spring-boot-starter-test, and a basic idea of how MockMvc works.
What to test
The document is JSON served over HTTP, so you can test it like any other endpoint. Different checks catch different problems.
| Check | Catches | Cost |
|---|---|---|
| Endpoint returns 200 and valid JSON | Broken setup, wrong path, security blocking the docs | Low |
| Specific paths, summaries and status codes | Lost annotations, renamed routes | Low |
| Schema constraints and security schemes | Validation or `@SecurityScheme` changes | Low |
| Parse with an OpenAPI parser | Structurally invalid documents | Medium |
| Compare with a committed snapshot | Any unintended change to the contract | Medium, needs upkeep |
| Profile tests for production | Docs exposed or unreachable in the wrong environment | Low |
Use a full application context
Springdoc registers its controllers and customizers through auto-configuration. A narrow slice test such as @WebMvcTest may not load all of them, and it will not load your OpenAPI bean or GroupedOpenApi beans unless you import them. Use @SpringBootTest with @AutoConfigureMockMvc. This also exercises the real Spring Security chain, which is what decides whether the docs are reachable.
A smoke test
import static org.hamcrest.Matchers.startsWith;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
class OpenApiSmokeTest {
@Autowired
private MockMvc mockMvc;
@Test
void documentIsServedWithMetadata() throws Exception {
mockMvc.perform(get("/v3/api-docs"))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.openapi").value(startsWith("3.")))
.andExpect(jsonPath("$.info.title").value("Library API"))
.andExpect(jsonPath("$.info.version").value("1.0.0"));
}
}If this fails with 401 or 403, your security filter chain is blocking the docs. If it fails with 404, check that the springdoc.api-docs.path property matches the path you request, and that the test is not running under a profile that disables the docs.
Assert on the parts you care about
Full-document comparison is brittle, so start with targeted assertions on the details your consumers depend on. JsonPath bracket notation handles path keys that contain slashes and braces.
import static org.hamcrest.Matchers.hasItems;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
class OpenApiContractTest {
@Autowired
private MockMvc mockMvc;
@Test
void getBookOperationIsDocumented() throws Exception {
mockMvc.perform(get("/v3/api-docs"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.paths['/api/books/{id}'].get.summary")
.value("Get a book by id"))
.andExpect(jsonPath("$.paths['/api/books/{id}'].get.responses['200']").exists())
.andExpect(jsonPath("$.paths['/api/books/{id}'].get.responses['404']").exists());
}
@Test
void bookSchemaReflectsValidationAndAnnotations() throws Exception {
mockMvc.perform(get("/v3/api-docs"))
.andExpect(jsonPath("$.components.schemas.Book.required")
.value(hasItems("title", "author")))
.andExpect(jsonPath("$.components.schemas.Book.properties.title.maxLength")
.value(200))
.andExpect(jsonPath("$.components.schemas.Book.properties.id.readOnly")
.value(true));
}
@Test
void bearerSchemeIsDeclared() throws Exception {
mockMvc.perform(get("/v3/api-docs"))
.andExpect(jsonPath("$.components.securitySchemes.bearerAuth.type").value("http"))
.andExpect(jsonPath("$.components.securitySchemes.bearerAuth.scheme").value("bearer"))
.andExpect(jsonPath("$.components.securitySchemes.bearerAuth.bearerFormat").value("JWT"));
}
}These tests protect the documented contract. If someone removes @Size(max = 200) from Book, the maxLength assertion fails, and the review shows that the API's public description changed.
Assert on what clients rely on: paths, status codes, required fields and security. Do not assert on every description string, or each wording change will break a test.
Check that the document is valid
A document can be JSON and still violate the OpenAPI specification. Tools such as client generators will reject it. The swagger-parser library reads and validates the document. Add it in test scope. Set ${swagger-parser.version} to a current 2.x release.
<dependency>
<groupId>io.swagger.parser.v3</groupId>
<artifactId>swagger-parser</artifactId>
<version>${swagger-parser.version}</version>
<scope>test</scope>
</dependency>import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.parser.core.models.SwaggerParseResult;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
class OpenApiValidityTest {
@Autowired
private MockMvc mockMvc;
@Test
void documentParsesWithoutMessages() throws Exception {
String json = mockMvc.perform(get("/v3/api-docs"))
.andReturn().getResponse().getContentAsString();
SwaggerParseResult result = new OpenAPIParser().readContents(json, null, null);
assertNotNull(result.getOpenAPI(), "document should parse");
assertTrue(result.getMessages() == null || result.getMessages().isEmpty(),
() -> "parser reported: " + result.getMessages());
}
}The assertion message prints the parser's findings, so a failure tells you what is wrong in the document.
Snapshot comparison
A snapshot test stores the expected document in src/test/resources and compares it with the live one. Any change to the API description fails the test until a person reviews it and updates the file. That makes accidental contract changes visible in code review.
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.StreamUtils;
@SpringBootTest
@AutoConfigureMockMvc
class OpenApiSnapshotTest {
@Autowired
private MockMvc mockMvc;
@Test
void documentMatchesCommittedSnapshot() throws Exception {
String actual = mockMvc.perform(get("/v3/api-docs"))
.andReturn().getResponse().getContentAsString();
String expected = StreamUtils.copyToString(
new ClassPathResource("openapi-expected.json").getInputStream(),
StandardCharsets.UTF_8);
JSONAssert.assertEquals(expected, actual, JSONCompareMode.STRICT);
}
}JSONAssert is part of spring-boot-starter-test. Snapshots have two known problems:
- Environment-dependent fields. Under MockMvc, springdoc fills the
serversentry from the request, so it readshttp://localhost. Keep the snapshot generated the same way, through this test, and not copied from a running server. If the field still causes trouble, useJSONCompareMode.LENIENTor removeserversfrom both sides before comparing. - Noise. Strict comparison fails on harmless changes such as a new description. Teams that update snapshots without reading the diff gain nothing, so reserve this test for APIs that external clients consume.
If you generate the specification at build time, as the previous chapter described, you can compare that generated file with the committed one in the same way. The test then never needs to start a server.
Test environment behavior
The production chapter set up two protections: permitAll rules for the docs, and a prod profile that disables them. Test both, because a wrong profile or a changed security rule breaks them silently. For the profile test, application-prod.yml must be on the test classpath.
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("prod")
class OpenApiProductionTest {
@Autowired
private MockMvc mockMvc;
@Test
void apiDocsAreNotServedInProduction() throws Exception {
mockMvc.perform(get("/v3/api-docs"))
.andExpect(status().isNotFound());
}
}The expected status depends on your security setup. With the earlier SecurityConfig, the docs paths are permitAll, so a disabled endpoint returns 404. If you remove that rule in production, an unauthenticated request returns 401 or 403 before routing reaches the missing endpoint. Decide which result you intend and assert it.
You can use the same approach for groups. Request /v3/api-docs/public and /v3/api-docs/admin, then check that $.paths['/admin/users'] does not exist in the public document. A doesNotExist() assertion is also the way to confirm that a hidden endpoint stays hidden.
Common errors
- The test passes locally but the document lacks your endpoint. A
springdoc.paths-to-matchvalue, such as/api/**, may exclude it. Check the effective properties for the test profile. jsonPathfails on a path key. Dot notation breaks on slashes and braces. Use$.paths['/api/books/{id}'].- The context fails to start in the test. Springdoc is not at fault here. A missing
BookServicebean or an absent database configuration is the usual cause. Fix the context as you would for any@SpringBootTest. - Tests are slow. Each distinct combination of profiles and properties creates a new application context. Keep the number of variations small and group related assertions in one class.
Exercise
A teammate removes @Size(max = 200) from the title field of Book. Which test in this chapter would fail, and why would a plain "status is 200" smoke test not notice?
Show answer
The targeted assertion on $.components.schemas.Book.properties.title.maxLength fails, because the generated schema no longer contains maxLength: 200. A snapshot comparison would fail too. The smoke test only checks that the document is served and has a title and version, and the endpoint still returns 200 without that constraint.
Exercise
You add a prod profile test that requests /v3/api-docs and expects 404, but it receives 401. What is the most likely cause, and what are your two options?
Show answer
The security filter chain no longer has a permitAll rule for the docs paths in that configuration, so the request is rejected before routing finds that the endpoint is disabled. Either keep the permitAll rule for the docs paths and expect 404, or accept that unauthenticated requests are blocked and change the test to expect 401.