MockMvc
With spring_boot_starter_web, app.mockMvc sends requests to the controllers in memory. It runs the same dispatcher a real server runs (filters, mapping, binding, @Valid, exception handlers and the ProblemDetail answers), without a socket, so it is fast and needs no free port. By default (WebEnvironment.mock) no server starts at all.
Why
A controller test should go through the real web layer: the path mapping, the JSON binding, the validation, the error answers. A socket adds nothing to that but slowness and port conflicts. When a client really needs a socket (a Feign client, dart:io's HttpClient, a WebSocket client), webEnvironment starts a real server on a free port.
Example
final app = springBootTest(springApplication);
test('finds, searches, rejects and deletes books', () async {
final mvc = app.mockMvc;
await mvc.get('/api/books/1111').andExpect(
status: 200,
contentType: MediaType.applicationJson,
headers: {'X-Trace': 'on'},
json: {'isbn': '1111', 'title': 'Dune'}, // or a matcher: containsPair('title', 'Dune')
);
await mvc.get('/api/books', params: {'q': 'dune'}).andExpect(json: hasLength(1));
// An empty ISBN fails validation: a 400 with a ProblemDetail body.
await mvc
.post('/api/books', json: {'isbn': '', 'title': ''})
.andExpect(status: 400, contentType: MediaType.applicationProblemJson);
await mvc.delete('/api/books/2222').andExpect(status: 204);
});
Each call returns a ResultActions, which is a Future: await it, or a failed expectation is never reported.
Requests
| Call | Sends |
|---|---|
get(path, headers:, params:) |
A GET |
post, put, patch(path, json:, body:, headers:) |
json encoded with Content-Type: application/json; body a String or bytes, sent as is |
delete(path, headers:) |
A DELETE |
multipart(path, files: [...], params: {...}) |
A multipart/form-data body, through the server's multipart parsing and limits |
perform(MockRequestBuilder(...)) |
Anything else |
webSocket(path) |
A WebSocket handshake in memory (spring_boot_starter_websocket) |
MockRequestBuilder(HttpMethod.get, '/api/books/{isbn}', ['978-0']) fills {name} placeholders from a list, and has headers, params, cookies, principal, content(...) and json(...).
Expectations
andExpect(status:, contentType:, headers:, body:, json:) checks only what is given:
contentTypematches compatible types (application/jsonmatchesapplication/json;charset=utf-8);bodyandjsontake a value or a matcher;- a failure names the request and shows the whole response;
- a
json:check on a body that is not JSON throws aFormatExceptionrather than reporting a failed expectation.
andDo((result) => ...) runs code with the result; andReturn() (or await) gives the MvcResult, with request and response (statusCode, headers, cookies, bodyText, bodyBytes, json).
Files, streams and WebSocket
- Uploads:
MockMultipartFile('cover', 'dune.png', 'image/png', bytes)is a file; one without a file name and withapplication/jsonis a JSON part for@RequestPart. - Downloads are read from
result.response.bodyBytes; sendRangeorIf-Modified-Sinceheaders like any other. - Server-sent events: the result is ready as soon as the headers are out. Read the events from
result.response.eventStream(eventsholds those so far), and end the stream withresult.cancel(). - WebSocket endpoints:
await mvc.webSocket('/ws/chat')returns the client'sWebSocketSession. A refused handshake throws aWebSocketExceptionwith the status and body.
test('streams the new orders', () async {
final result = await app.mockMvc.get('/api/orders/stream');
final first = await result.response.eventStream.first;
expect(first.data, contains('"id"'));
await result.cancel();
});
Request post-processors
A RequestPostProcessor changes a request just before it is sent: a logged-in user, a CSRF token, a header. Add one to a request with builder.with_(processor), or to every request with MockMvc(app.getBean<DispatcherHandler>(), defaultPostProcessors: [...]). package:spring_boot_starter_security/testing.dart provides user(...), jwt(), csrf() and others.
A real server: webEnvironment
final app = springBootTest(springApplication, webEnvironment: WebEnvironment.randomPort);
test('over HTTP', () async {
final url = Uri.parse('http://localhost:${app.localServerPort}/api/books/1111');
final response = await HttpClient().getUrl(url).then((r) => r.close());
expect(response.statusCode, 200);
});
webEnvironment |
Spring | Server |
|---|---|---|
WebEnvironment.mock (default) |
MOCK |
None; use app.mockMvc |
WebEnvironment.randomPort |
RANDOM_PORT |
A real one on a free port (server.port=0); the context counts as started once it listens; app.localServerPort gives the port (local.server.port) |
WebEnvironment.definedPort |
DEFINED_PORT |
A real one on server.port; the start fails when the port is taken |
WebEnvironment.none |
NONE |
None; app.mockMvc still works |
It sets spring.test.web-environment (mock, random-port, defined-port, none). app.localServerPort throws a StateError when no real server runs; app.mockMvc throws one without the web starter.
In a test class: @SpringBootTest(webEnvironment: WebEnvironment.randomPort), a @LocalServerPort() late int port; field, and an @Autowired() late MockMvc mvc; field.
In Spring (Java)
mockMvc.perform(get("/api/books/1111"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("Dune"));
Differences: no @AutoConfigureMockMvc needed; andExpect takes named checks with matchers instead of status().isOk() and jsonPath(...); there is no WebTestClient or TestRestTemplate (use a Feign client or HttpClient against localServerPort).