
# Testing

A test class marked `@DataTest()` starts only the data layer of the application: its repositories and data beans, an in-memory SQLite database with your migrations applied, and a transaction around every test that is rolled back afterwards. Services, controllers and runners are not in the context. `spring_boot_starter_test` runs it.

## Why

A repository test needs the repositories, a real database and a clean slate for every test. Starting the whole application is slow and brings beans the test does not need; sharing data between tests makes them depend on their order. `@DataTest` is Spring's `@DataJdbcTest` with `@AutoConfigureTestDatabase`: a small context, a fresh database, and a rollback after each test.

## Example

```yaml
# pubspec.yaml
dependencies:
  spring_boot_starter_data: ^0.9.0
  sqlite3: ^3.8.0                     # required: the test database is SQLite

dev_dependencies:
  build_runner: ^2.17.0
  spring_core_dart_generator: ^0.9.0
  spring_boot_starter_test: ^0.9.0
  test: ^1.33.0
```

```dart
// test/book_repository_test.dart
import 'package:spring_boot_starter_data/spring_boot_starter_data.dart';
import 'package:spring_boot_starter_test/spring_boot_starter_test.dart';
import 'package:test/test.dart';

import 'spring_gen/book_repository.test.spring.dart'; // generated

@DataTest()
class BookRepositoryTest {
  @Autowired()
  late BookRepository books;

  @BeforeEach()
  Future<void> seed() async {                     // runs inside the test's transaction
    await books.save(Book(title: 'Dune', year: 1965));
  }

  @Test()
  Future<void> findsABookByItsTitle() async {
    await books.save(Book(title: 'Emma', year: 1815));
    expect(await books.findByTitle('Emma'), hasLength(1));
  }                                               // rolled back

  @Test()
  Future<void> startsWithTheSeedOnly() async {
    expect(await books.count(), 1);               // no 'Emma' from the test before
  }
}

void main() => runSpringTests();
```

```bash
dart run build_runner build    # writes test/spring_gen/book_repository.test.spring.dart
dart test
```

The class is written like a `@SpringBootTest` one: `@Autowired()` fields, `@Test()` methods, `@BeforeEach`, `@Nested`, `@ActiveProfiles`, `@TestPropertySource` and `@TestBean` work the same. A class has `@SpringBootTest()` or `@DataTest()`, not both.

## What the context holds

- **The data beans of the application:** its repositories, the description of its entities, the driver bean for `sqlite3`, the beans of the types the starter uses or replaces (`DataSource`, `PlatformTransactionManager`, `TransactionTemplate`, `JdbcTemplate`, `NamedParameterJdbcTemplate`, `JdbcClient`, `DataStore`, `NamingStrategy`, `AuditorAware`, `DateTimeProvider`, `RepositoryFactory`...), and the class that carries `@EnableDataAuditing`.
- **The auto-configuration of the data starter**, the core and logging. That of other starters (web, cache, security, scheduling...) is left out.
- **Nothing else.** A bean left out is absent: an `@Autowired() late Library? library;` field stays `null`, and a kept bean that needs one fails the start with the usual report.
- **`include`** adds beans of the application by the type of their class: `@DataTest(include: [Library, ShopConfig])`. A configuration class brings all its `@Bean` methods.

## The database

When the application configures a SQL database, `@DataTest` replaces it with an in-memory SQLite database before the context starts:

| Property | Set to | Why |
|---|---|---|
| `spring.datasource.url` | `sqlite::memory:` | The database lives as long as its connection. |
| `spring.datasource.driver` | `sqlite3` | Whatever the configuration named. |
| `spring.datasource.pool.max-size` | `1` | Each SQLite connection has its own in-memory database. |
| `spring.datasource.pool.min-idle`, `idle-timeout`, `max-lifetime` | `0` | The pool never closes the one connection and loses the data. |

Every other setting stays, and the same happens to each `spring.datasources.<name>.url`. Without a configured database nothing is replaced: the repositories use the in-memory store, as in the application.

- **`replaceDatabase: false`** keeps the configured database, for example one a container started. The tests still roll back.
- **The `sqlite3` driver is required** to replace a database; without it the start fails and says so.
- **A `DataSource` bean of your own** (one the properties do not describe) is not replaced.
- **One connection means one transaction.** Code that starts its own transaction (`Propagation.requiresNew`) waits for a second connection and fails after `pool.connection-timeout`. Test it with `replaceDatabase: false` on a database with several connections.

The schema comes from where it comes from in the application: migrations are applied (and the entities validated), or `schema.sql` and `data.sql` run, or, without either, the tables are created from the entities.

## The transaction

Each test runs in a transaction of every transaction manager its repositories write through (the primary database's, the in-memory store's, the named databases'), rolled back at its end.

- `@BeforeEach` and `@AfterEach` run inside the transaction, as in Spring; `@BeforeAll` and `@AfterAll` run outside.
- **`@Commit()`** (or `@Rollback(false)`) on a test, a class or a `@Nested` group commits instead; the innermost one wins. A failing test is rolled back even then, so a failure leaves nothing behind (Spring would commit).
- **`@DataTest(transactionManager: 'stats')`** runs the tests in the transaction of that one manager and no other: the other databases are written for real.
- **`@Transactional(transactionManager: 'stats')`** on a test method, a `@Nested` group or a class picks the manager for the tests inside; the innermost wins. Its other attributes do nothing on a test.
- Callbacks that wait for a commit run only for tests that commit.

## Options

| Option | Default | Meaning |
|---|---|---|
| `application` | the package's only application | The application whose beans are used (Spring's `classes`). |
| `args` | `[]` | Command line arguments. |
| `properties` | `{}` | Properties for the test. |
| `resourceDirectories` | `['test/resources']` | Extra resource directories. |
| `include` | `[]` | Beans of the application to add, by type. |
| `replaceDatabase` | `true` | Replace the configured database with an in-memory SQLite one. |
| `transactionManager` | `''` | The one manager whose transaction the tests run in; empty for every manager the repositories use. |

## Tests written as functions

`DataTestSetup` and `runInTestTransaction`, from `package:spring_boot_starter_data/testing.dart`, do the same without a class:

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

void main() {
  final data = DataTestSetup(springApplication);
  final app = springBootTest(
    springApplication,
    properties: data.properties,        // other starters' auto-configuration out
    initializers: [data.initializer],   // database replaced, beans left out
  );

  test('finds a book', () => runInTestTransaction(app.context, () async {
    final books = app.getBean<BookRepository>();
    await books.save(Book(title: 'Dune', year: 1965));
    expect(await books.findByTitle('Dune'), hasLength(1));
  }));
}
```

## In Spring (Java)

```java
@DataJdbcTest
class BookRepositoryTest {
  @Autowired BookRepository books;

  @Test void findsABookByItsTitle() { ... }
}
```

`@DataTest` replaces `@DataJdbcTest` with `@AutoConfigureTestDatabase`. It is transactional by itself, and the test database is always an in-memory SQLite one (`replaceDatabase: false` keeps yours). A failing `@Commit` test is rolled back.

## See also

- [Repositories](repositories.md)
- [SQLite](sqlite.md)
- [Testing a web application](../spring-boot-starter-web/testing.md)
