
# Test classes

The tests of [springBootTest](spring-boot-test.md) can be written as classes, the way Spring writes them. The generator (`spring_core_dart_generator`, already a dev dependency) turns each class into the same functions, in `test/spring_gen/<name>.test.spring.dart`.

## Why

A Spring developer reads `@SpringBootTest`, `@Autowired` and `@Test` at a glance. Test classes keep that shape: the class holds the test's beans and its test methods, and the annotations above it say how the application starts.

## Example

```dart
// test/checkout_test.dart
import 'package:spring_boot_starter_test/spring_boot_starter_test.dart';
import 'package:test/test.dart';

import 'spring_gen/checkout.test.spring.dart'; // generated, in test/spring_gen/

@SpringBootTest(args: ['--shop.name=Night Books'])
@ActiveProfiles(['dev', 'test'])
@TestEnvironment({'SHOP_MAX_BASKET_SIZE': '25'})
class CheckoutTest {
  @Autowired()
  late ShopProperties properties;

  @Autowired()
  late Checkout checkout;

  @TestBean(name: 'sandbox')
  final gateway = FakeGateway();

  @Test()
  void propertiesFromTheCommandLineAndTheEnvironment() {
    expect(properties.name, 'Night Books');
    expect(properties.maxBasketSize, 25);
  }

  @Test('checkout pays through the fake')
  void pays() {
    checkout.pay(3);
    expect(gateway.charged, [3]);
  }
}

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

- **`main` stays.** `dart test` runs a file's `main`, and the generator cannot write into your file. `runSpringTests()` comes from the generated file and runs every test class of the file.
- **Plain tests** that need no context can sit next to it in `main`.

## Class annotations

| Annotation | `springBootTest` parameter | Spring |
|---|---|---|
| `@SpringBootTest(application:, args:, properties:, resourceDirectories:, webEnvironment:)` | first argument, `args:`, `properties:`, `resourceDirectories:`, `webEnvironment:` | `@SpringBootTest` |
| `@ActiveProfiles(['dev', 'test'])` | `profiles:` | `@ActiveProfiles` |
| `@TestPropertySource(properties: {...}, locations: [...])` | `properties:`, `propertyFiles:` | `@TestPropertySource` |
| `@TestEnvironment({'NAME': 'value'})` | `systemEnvironment:` | none |
| `@DirtiesContext()` | `setUp(app.markDirty)` | `@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)` |
| `@AutoConfigureMockMvc()` | nothing: `MockMvc` always works | `@AutoConfigureMockMvc` |
| `@Testcontainers()` | see [Containers](containers.md) | `@Testcontainers` |

`application` is a path to an entry point with `@SpringBootApplication` (`'bin/admin.dart'`), needed only when the package has several. It may point anywhere in the package, so a starter's tests can start an application of their own under `test/`.

## Fields

| Annotation | On | Gets |
|---|---|---|
| `@Autowired()` | `late` field | A bean, set before every test (after a restart, the new context's bean). `@Qualifier('x')` picks one of several |
| `@Value(r'${key}')` | `late` field | A property, converted |
| `@TestBean()` | field with a value | Replaces a bean; see [BeanOverride and @TestBean](bean-override.md) |
| `@LocalServerPort()` | `late int` field | The port of the real server |
| `@CapturedOutput()` | `late CapturedLogs` field | The logs of each test; see [Captured logs](captured-logs.md) |
| `@Nested('name')` | field holding an instance | A group of tests with the same context |
| `@Container()` | `static` field | A Docker container; see [Containers](containers.md) |

- A field must be `late`, public and not `final` (except `@TestBean`, `@Nested` and `@Container` fields).
- The types are those of constructor injection: a nullable field is optional; `List<T>`, `Iterable<T>`, `Set<T>`, `Map<String, T>` and `ObjectProvider<T>` work; `ApplicationContext`, `Environment`, `SpringBootTestContext` and `MockMvc` are recognised by name.
- The generated code creates the class with `Name()`, so it must be public, not abstract, and have an unnamed constructor without required parameters. There is no constructor injection.
- Annotated members of a superclass declared in the same file count; a superclass in another file is not seen, and the build warns.

## Methods

| Annotation | Meaning |
|---|---|
| `@Test([name])` | A test; without a name, the method name split into words (`addsABook` is `adds a book`). A returned `Future` is awaited |
| `@DisplayName(name)` | The test's name; wins over `@Test(name)` |
| `@Disabled([reason])` | Skips the test (on the class or a `@Nested` field: all of it), shown with the reason |
| `@Tag(name)` | A tag for `dart test --tags` / `--exclude-tags`; several allowed |
| `@TestOptions(timeout:, retry:, testOn:, onPlatform:)` | The other options of `test()` |
| `@DirtiesContext()` | A new context after this test |
| `@BeforeAll()` | Static; once, before the context starts |
| `@BeforeEach()` | Before every test, after the fields were injected |
| `@AfterEach()` | After every test, before a `@DirtiesContext` restart |
| `@AfterAll()` | Static; once, after the context is closed |
| `@DynamicPropertySource()` | Static; registers dynamic properties at every start |
| `@ContextInitializer()` | Static; an initializer run before the refresh |

Tests run in the order of the methods. Several methods with the same before or after annotation run in the order of the class.

```dart
@SpringBootTest()
class OrdersTest {
  @Autowired()
  late Orders orders;

  @BeforeAll()
  static Future<void> startDatabase() async { ... }   // before the context starts

  @BeforeEach()
  void clear() => orders.clear();                      // the beans are injected by now

  @Test()
  @Tag('slow')
  @TestOptions(timeout: Timeout(Duration(seconds: 5)), retry: 2)
  Future<void> placesAnOrder() async { ... }

  @Test()
  @DirtiesContext()                                    // a new context after this test
  void changesSharedState() { ... }
}
```

## Groups: @Nested

Dart has no inner classes, so a group is a field holding an instance of its own class. It runs as a `group` with the same context and beans; its `@BeforeEach` methods run after the outer ones.

```dart
@SpringBootTest()
class BasketTest {
  @Nested('with one book')
  final withOneBook = WithOneBook();
}

class WithOneBook {
  @Autowired()
  late Basket basket;               // the same bean as in the outer class

  @BeforeEach()
  void addBook() => basket.add('Dune', 10);

  @Test()
  void costsItsPrice() => expect(basket.total, 10);
}
```

A nested class may not have `@TestBean` fields or `@BeforeAll`, `@AfterAll`, `@DynamicPropertySource` and `@ContextInitializer` methods: they belong to the outer class, which owns the context.

## @DirtiesContext on a class

It restarts the context after each test of the class, Spring's `classMode = AFTER_EACH_TEST_METHOD`. Spring's default for a class (`AFTER_CLASS`) is what every class gets here anyway, as each class starts its own context. There is no `classMode` or `methodMode`.

## Build errors

The generator checks the classes and stops the build with a message for mistakes such as a `final` `@Autowired` field, a `@TestBean` field without a type to replace, a static `@Test` method, or an `application` path that is no entry point. See [The generator: tests](../spring-core-dart-generator/tests.md).

## In Spring (Java)

```java
@SpringBootTest(args = "--shop.name=Night Books")
@ActiveProfiles({"dev", "test"})
class CheckoutTest {
  @Autowired ShopProperties properties;
  @TestBean(name = "sandbox") PaymentGateway gateway;
  static PaymentGateway gateway() { return new FakeGateway(); }

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

Differences: fields only (no constructor injection), `main() => runSpringTests()` stays, groups are `@Nested` fields, and `@Tag`, `@Disabled` and `@TestOptions` bring `package:test`'s library annotations to single tests.

## See also

- [springBootTest](spring-boot-test.md)
- [Test properties](test-properties.md)
- [The generator: tests](../spring-core-dart-generator/tests.md)
