Sub topic 12
Testing Versioned Endpoints
This chapter shows how to test versioned Spring MVC endpoints at three levels: a slice test, a full-context test, and a real HTTP call with RestClient. It assumes you have read the earlier chapters on ApiVersionConfigurer, the version attribute, default versions and the error behavior for bad versions. It also assumes you know JUnit 5 and MockMvc basics.
What a versioning test must prove
A versioned endpoint has more failure modes than a plain one. The same path can reach different handlers, and the choice depends on a header, a configured default and a list of supported versions. Tests should cover each decision the router makes.
| Behavior | Request | Expected outcome |
|---|---|---|
| Fixed version | `X-API-Version: 1.0` | The `1.0` handler runs |
| Baseline version | `X-API-Version: 2.0` | The `2.0+` handler runs |
| Later version in a baseline range | `X-API-Version: 2.1` | The `2.0+` handler runs, if `2.1` is supported |
| Default version | No header | The handler for the default version runs |
| Unsupported version | `X-API-Version: 3.0` | A client error, `400 Bad Request` |
Each row is a decision in the request path. The diagram below shows the path.
Slice test with MockMvc
A slice test loads only the web layer, so it starts quickly. It is the best place for most version tests, because versioning is purely a routing concern. The controller and the ApiVersionConfig class are the only beans you need.
The test below uses the controller and configuration from the earlier chapters. It adds a small test configuration that declares version 2.1 as supported. addSupportedVersions adds to the existing list, so the application configuration stays in effect. Without 2.1 in the list, you could not check that a baseline mapping covers later versions.
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.servlet.config.annotation.ApiVersionConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
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;
@WebMvcTest(AccountController.class)
@Import({ApiVersionConfig.class, AccountVersionTests.ExtraVersion.class})
class AccountVersionTests {
@TestConfiguration
static class ExtraVersion implements WebMvcConfigurer {
@Override
public void configureApiVersioning(ApiVersionConfigurer configurer) {
configurer.addSupportedVersions("2.1");
}
}
@Autowired
MockMvc mockMvc;
@Test
void version1ReturnsSingleNameField() throws Exception {
mockMvc.perform(get("/accounts/1").header("X-API-Version", "1.0"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Ada Lovelace"))
.andExpect(jsonPath("$.firstName").doesNotExist());
}
@ParameterizedTest
@ValueSource(strings = {"2.0", "2.1"})
void baselineMappingServesVersion2AndLater(String version) throws Exception {
mockMvc.perform(get("/accounts/1").header("X-API-Version", version))
.andExpect(status().isOk())
.andExpect(jsonPath("$.firstName").value("Ada"))
.andExpect(jsonPath("$.lastName").value("Lovelace"))
.andExpect(jsonPath("$.name").doesNotExist());
}
@Test
void missingHeaderFallsBackToDefaultVersion() throws Exception {
mockMvc.perform(get("/accounts/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Ada Lovelace"));
}
@Test
void unsupportedVersionIsRejected() throws Exception {
mockMvc.perform(get("/accounts/1").header("X-API-Version", "3.0"))
.andExpect(status().isBadRequest());
}
}Three habits in this test are worth copying.
- Assert the shape, not only the status. Both handlers return
200 OK, so a status check alone cannot tell which handler ran. ThedoesNotExist()checks prove that the other version's fields are absent. That guards against a mapping that quietly serves the wrong representation. - Test the default on purpose. The no-header test fails if someone changes
setDefaultVersion. A changed default silently changes what every unversioned client receives, which is a breaking change in disguise. - Test the edge of a baseline range. A parameterized test over
2.0and2.1shows that2.0+is open-ended. If you later add3.0to the supported list, you will see at once which tests need a new handler.
Testing the whole application
The slice test replaces your real configuration with an explicit import. A full-context test checks that the real application wiring works. That includes the Spring Boot properties from the earlier chapter, if you configure versioning that way instead of with a WebMvcConfigurer.
The test below is the one from the Topic Spine. It runs against the whole context.
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
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;
@SpringBootTest
@AutoConfigureMockMvc
class AccountVersioningTests {
@Autowired
MockMvc mockMvc;
@Test
void version2ReturnsSplitName() throws Exception {
mockMvc.perform(get("/accounts/1").header("X-API-Version", "2.0"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.firstName").value("Ada"));
}
}Keep one or two tests like this as a smoke check. Put the detailed cases in the slice class. Full-context tests are slower, and you gain nothing by repeating every case in them.
If you configure versioning with properties, you can vary the configuration per test class. Set the properties in the annotation:
@SpringBootTest(properties = {
"spring.mvc.apiversion.default=2.0"
})
@AutoConfigureMockMvc
class DefaultVersionTwoTests {
// The same request without a header now reaches the 2.0+ handler.
}This lets you pin the default in a test and check that clients without a header get the version you expect.
Testing with a real HTTP call
MockMvc skips the servlet container and the network. It never exercises the client side of versioning. A RestClient configured with an ApiVersionInserter is part of your code too. If it is wrong, every call from your service goes out with the wrong header or none at all.
Start the application on a random port and call it with a real client. This test checks both sides at once: the server routes by version, and the client inserts the header.
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.web.client.ApiVersionInserter;
import org.springframework.web.client.RestClient;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class AccountClientTests {
@LocalServerPort
int port;
@Test
void clientRequestsVersion2() {
RestClient client = RestClient.builder()
.baseUrl("http://localhost:" + port)
.apiVersionInserter(ApiVersionInserter.useHeader("X-API-Version"))
.build();
String body = client.get()
.uri("/accounts/1")
.apiVersion("2.0")
.retrieve()
.body(String.class);
assertThat(body).contains("\"firstName\":\"Ada\"");
}
}The inserter must match the server's resolver. If the server reads a header and the client writes a query parameter, the server sees no version and applies the default. Such a test can pass for version 1.0 by accident, because 1.0 is the default. Always include at least one client test for a non-default version, as above.
Common test failures and what they mean
- A
2.0request returns the1.0body. The test is probably missing the header, so the default applied. Check the header name for typos. It must match the name given touseRequestHeaderexactly. - A slice test returns
404or a version error for every versioned path. The@WebMvcTestcontext did not load your versioning configuration. Add it with@Import, as the slice example does. - A
2.1request is rejected although2.0+exists. Version2.1is not in the supported list. A baseline range only covers versions that are supported, so declare the version first. - A test passes alone but fails in the suite. A test that sets properties through
@SpringBootTest(properties = ...)creates a separate cached context. If another test mutates shared state, the order can matter. Keep controllers stateless in tests.
Structuring the test suite
A practical split for a team:
- A slice test class per controller, covering fixed versions, baseline ranges, default and unsupported versions.
- One full-context smoke test per application, using the real configuration or properties.
- One client test per
RestClientorWebClientbean that has an inserter. - When you retire a version, delete its tests in the same commit that removes its handler and its supported-version entry. A test for a removed version should instead assert that the request is now rejected.
That last point makes retirement visible. The test that asserted 1.0 returns data becomes a test that asserts 1.0 returns 400. The change documents the end of support.
Exercise
A controller has mappings version = "1.0" and version = "2.0+". The supported versions are 1.0, 1.1 and 2.0, and the default is 1.0. You add 3.0 to the supported versions but write no new handler. Which existing test would you add or extend to learn which handler serves a 3.0 request, and what do you assert?
Show answer
Extend the parameterized baseline test with 3.0 in its @ValueSource. Send X-API-Version: 3.0 and assert status().isOk(), jsonPath("$.firstName") equal to "Ada", and jsonPath("$.name").doesNotExist(). Because 2.0+ is a baseline range, the getV2 handler serves 3.0. The test makes that implicit decision explicit, so a team that wants a different 3.0 representation must add a handler and change the test.
Exercise
Your client test passes, but in production the service receives the 1.0 representation even though the code calls .apiVersion("2.0"). The server resolves versions from the X-API-Version header. Name two things in the client test that could have hidden the bug, and how to fix them.
Show answer
First, the test may have requested 1.0 or no version, which is the default, so the server returned the right body even if the header was never sent. Fix it by requesting a non-default version such as 2.0 and asserting a field that only that version returns. Second, the test may have built its RestClient without the same ApiVersionInserter that production uses, for example a different header name or none. Fix it by building the client from the same factory or configuration as production, or by asserting the exact header with the same ApiVersionInserter.useHeader("X-API-Version") setup.