Spring integration tests
What you will learn
Spring tests load different amounts of infrastructure. A MVC slice focuses on web-layer behavior, a full application context checks wiring, and a random-port test sends actual HTTP. A passing controller test does not prove that security filters, transactions, or serialization are configured correctly elsewhere.
- Choose a Spring test slice or full context by claim.
- Distinguish mock MVC dispatch from a listening server.
- Test both accepted and rejected tenant lookup cases.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Framework examples require the companion Maven project or are reviewed artifacts. Their predicted results are not execution evidence.
Test tenant keys as a pair
public class Main { record Key(String tenant,String sku) {} public static void main(String[] args) {var records=java.util.Map.of(new Key("alpha","pen"),4); System.out.println(records.getOrDefault(new Key("alpha","pen"),-1)); System.out.println(records.getOrDefault(new Key("beta","pen"),-1)); }}Expected output:
4-1The lookup never falls back to a different tenant; the number -1 is a test sentinel, not an HTTP result.
Test layers in Boot 4
@WebMvcTest lives in the webmvc test module in Boot 4. It selects MVC components, and @MockitoBean can supply a missing collaborator. MockMvc exercises dispatch, binding and serialization without a TCP listener. @SpringBootTest loads the application context; with @AutoConfigureMockMvc it still uses mock HTTP by default. RANDOM_PORT starts an embedded server. WebTestClient can bind to a mock reactive application or a real server; those are different evidence layers.
Security and isolation
Never disable security filters merely to turn a denial into a passing test. Test anonymous, allowed and denied principals, including different tenants with the same resource ID. The lab header is synthetic routing context only; real tenant identity must come from authenticated and authorized claims. A shared Spring context may be cached across test classes; use fresh data and do not depend on test order. A transaction on the test thread does not roll back a real server request handled by another thread.
Check failure recovery without a global fixture
public class Main {
public static void main(String[] args) {var a=new java.util.HashMap<String,Integer>(); a.put("pen",4); var b=new java.util.HashMap<String,Integer>(); System.out.println(a.size()); System.out.println(b.size()); }}Expected output:
10Each test should own its data. This model does not exercise Spring context caching.
MVC slice with stub service
Source-reviewed, NOT RUN. File lab-fixtures/enterprise-testing-v46/src/test/java/lab/CatalogSliceTest.java; use the companion lab README.
package lab;import java.util.Optional;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;import org.springframework.test.context.bean.override.mockito.MockitoBean;import org.springframework.test.web.servlet.MockMvc;import static org.mockito.Mockito.*;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;@WebMvcTest(CatalogController.class)class CatalogSliceTest { @Autowired MockMvc mvc; @MockitoBean Catalog catalog; @Test void routeAndJson() throws Exception { when(catalog.find("alpha", "pen")).thenReturn(Optional.of(new Catalog.Item("pen", 4))); mvc.perform(get("/items/pen").header("X-Lab-Tenant", "alpha")) .andExpect(status().isOk()).andExpect(jsonPath("$.quantity").value(4)); mvc.perform(get("/items/pen")).andExpect(status().isBadRequest()); verify(catalog).find("alpha", "pen"); }}Predicted behavior: Valid request yields JSON; missing header returns 400.
The selected controller and binding are tested without a socket.
Full context and real service
Source-reviewed, NOT RUN. File lab-fixtures/enterprise-testing-v46/src/test/java/lab/CatalogContextTest.java; use the companion lab README.
package lab;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;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.*;@SpringBootTest@AutoConfigureMockMvcclass CatalogContextTest { @Autowired MockMvc mvc; @Test void realServiceBoundary() throws Exception { mvc.perform(get("/items/pen").header("X-Lab-Tenant", "alpha")) .andExpect(status().isOk()).andExpect(jsonPath("$.sku").value("pen")); mvc.perform(get("/items/pen").header("X-Lab-Tenant", "beta")) .andExpect(status().isNotFound()); }}Predicted behavior: Alpha gets 200; beta gets 404.
The real service participates but the HTTP layer is still mocked.
Common mistakes
Avoid treating @SpringBootTest as a synonym for end-to-end. Do not use a spoofable request header as authentication or assume a test-thread transaction resets server state.
Practice
Create a map with the same SKU in two tenants and assert the two values are independent.
Expected output:
8Compare with the manual review criteria.
Official reading: Spring MVC tests · Boot testing. External test execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Spring integration tests — knowledge check
Enterprise testing reasoning.
What does MockMvc omit?
Which annotation replaces a Spring collaborator in a slice?
How start a real embedded server?
What should a cross-tenant denial test use in production?
Does test transaction rollback automatically cover server-thread writes?