
# Testing

`package:spring_web_dart/testing.dart` has fakes for both sides. `MockHttpTransport` answers HTTP requests with responses prepared in advance and records what was sent; `MockWebSocketTransport` plays the server of every WebSocket connection; `MockServerHttpRequest`, `MockServerHttpResponse` and `WebSocketSessionPair` stand for the server's types. In a Spring Boot application, import them from `spring_boot_starter_test`, the test dependency the application has anyway.

## Why

Code that calls other services should be tested without them: no network, no flaky timing, and the test decides what the service answers, failures included.

## MockHttpTransport

```dart
import 'package:spring_web_dart/testing.dart';

final transport = MockHttpTransport();
transport.when(HttpMethod.get, '/books/1').respond(200, json: {'isbn': '1', 'title': 'Dune'});
transport.when(HttpMethod.get, '/books?q=dune').respond(200, json: []); // the query must match
transport.when(HttpMethod.get, 'https://api.neon.books/stock').respond(503);

// A retry test: the first call fails, the second one succeeds.
transport.when(HttpMethod.get, '/flaky').fail(HttpTransportException('down'));
transport.when(HttpMethod.get, '/flaky').respond(200, body: 'up');

// An answer computed from the request: echo the posted book.
transport
    .when(HttpMethod.post, '/books')
    .respondWith((request) => HttpResponse(201, body: request.body!, request: request));

// In a Spring Boot test, the Feign clients then talk to the mock.
final app = springBootTest(springApplication, overrides: [BeanOverride<HttpTransport>(transport)]);

expect(transport.lastRequest.headers['Accept'], 'application/json');
expect(transport.requests, hasLength(2));
```

| Call | Answers |
|---|---|
| `respond(status, json:, body:, headers:)` | A prepared response. |
| `respondWith((request) => response)` | A response computed from the request. |
| `fail(exception)` | Throws, as a network failure. |
| `respondEvents([...], keepOpen:)` | A `text/event-stream` body; data that is not a `String` is written as JSON. |
| `respondStream(status, () => chunks)` | Any streamed body. |

- Several answers for the same request are used in order, and the last one repeats.
- A request nobody prepared throws a `StateError` that lists the prepared ones.
- `requests` and `lastRequest` record what was sent.

```dart
transport
  ..when(HttpMethod.get, '/orders/events').respondEvents([
    ServerSentEvent({'id': 1, 'status': 'NEW'}, id: '1'),
  ])
  ..when(HttpMethod.get, '/orders/events').respond(204); // the reconnect stops
```

## MockWebSocketTransport

```dart
final sockets = MockWebSocketTransport();
// In a Spring Boot test: overrides: [BeanOverride<WebSocketTransport>(sockets)]

final server = await sockets.nextConnection;    // waits for the client to connect
server.pushJson({'from': 'ann', 'text': 'hi'}); // server → client
expect(server.sentJson, [{'text': 'hello'}]);   // what the client sent
await server.drop();                            // connection lost (1006)
sockets.failNextConnect();                      // the next connect fails
```

## Server-side mocks

| Type | What |
|---|---|
| `MockServerHttpRequest` | A request for a filter or a handler under test. |
| `MockServerHttpResponse` | Records the answer: `bodyText`, `json`, and `events` and `eventStream` for server-sent events. |
| `WebSocketSessionPair` | Two sessions connected in memory. |
| `MockMultipartFile` | The test file for `MockMvc.multipart`. |

An application gets them, with `MockMvc` on top, from `spring_boot_starter_test` (see [Testing in the web starter](../spring-boot-starter-web/testing.md)).

## In Spring (Java)

```java
MockRestServiceServer server = MockRestServiceServer.bindTo(restTemplate).build();
server.expect(requestTo("/books/1")).andRespond(withSuccess(json, MediaType.APPLICATION_JSON));
```

`MockHttpTransport` plays the role of Spring's `MockRestServiceServer`, at the transport level, so it serves every client built on `HttpTransport`. `MockWebSocketTransport` has no Spring counterpart.

## See also

- [HTTP transport](http-transport.md)
- [WebSocket transport](websocket-transport.md)
- [Testing Feign clients](../spring-boot-starter-feign/testing.md)
