
# springBootTest

`springBootTest` starts the application for the tests of the enclosing `main` or `group`. It does everything `runApplication` does: reads the config files, applies the auto-configuration, binds `@ConfigurationProperties`, calls the runners. It is Spring's `@SpringBootTest`.

## Why

Some tests need the real wiring: a service with its repositories, properties from the config files, controllers behind `MockMvc`. Starting the application once for a group of tests keeps them fast, and the options let each test file change only what it must, such as one property or one bean.

## Example

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

import '../bin/spring_gen/main.spring.dart';

void main() {
  final gateway = FakeGateway();

  final app = springBootTest(
    springApplication,
    args: ['--shop.name=Night Books'],                  // as on the command line
    properties: {'logging.console.enabled': false},     // win over every other source
    profiles: ['test'],                                 // spring.profiles.active
    systemEnvironment: {'SHOP_MAX_BASKET_SIZE': '25'},  // instead of the machine's
    overrides: [BeanOverride<PaymentGateway>(gateway)],
  );

  test('pays through the fake', () {
    app.getBean<Checkout>().pay(10);
    expect(gateway.charged, [10]);
  });

  test('changes shared state', () {
    app.getBean<Basket>().add(book);
    // The basket is not empty any more: the next test gets a new context.
    app.markDirty();
  });
}
```

`springBootTest` returns at once; the application starts before the first test.

## How it runs

- The context starts once, in a `setUpAll`, before the first test of the `main` or `group`. It is closed with `closeAsync()` in a `tearDownAll` after the last test, so asynchronous `@PreDestroy` methods and lifecycle stops are awaited.
- `app.markDirty()` closes the context at the end of the current test; the next test starts a new one. `setUp(app.markDirty)` gives every test a fresh context.
- `app` is usable inside tests, `setUp`, and a `setUpAll` declared after the `springBootTest` call. Elsewhere `app.context` throws a `StateError`, because the context does not exist yet.
- The `SpringLog` levels and handler the application changed are restored after the last test.
- Each `springBootTest` starts its own context; there is no cache shared between test files.

## The options

| Parameter | What it does | Spring |
|---|---|---|
| first argument | The `SpringApplication` to start, usually the generated `springApplication` | `classes` |
| `args` | Command-line arguments | `@SpringBootTest(args)` |
| `properties` | Properties above every other source, the command line and `propertyFiles` included | `@SpringBootTest(properties)` |
| `propertyFiles` | Resource locations of `.properties` files; later files win; a missing file fails the start with a `StateError` | `@TestPropertySource(locations)` |
| `dynamicProperties` | Properties known only when the tests run; above `properties` | `@DynamicPropertySource` |
| `profiles` | Become `spring.profiles.active`, replacing the value of the config files | `@ActiveProfiles` |
| `systemEnvironment` | The environment variables the application sees; empty by default | none |
| `resourceDirectories` | Directories first on the classpath; default `['test/resources']` | the test classpath |
| `overrides` | Beans replaced by fakes or mocks | `@MockitoBean`, `@TestBean` |
| `initializers` | `ApplicationContextInitializer`s run before the refresh | `@ContextConfiguration(initializers)` |
| `webEnvironment` | Which web server starts: `mock` (none, the default), `randomPort`, `definedPort`, `none` | `@SpringBootTest(webEnvironment)` |

See [Test properties](test-properties.md) for the precedence of the property options, [BeanOverride](bean-override.md) for `overrides` and [MockMvc](mock-mvc.md) for `webEnvironment`.

## SpringBootTestContext

What `springBootTest` returns:

| Member | What it gives |
|---|---|
| `getBean<T>({qualifier})`, `getBeanByName(name)` | A bean; throws when there is none |
| `findBean<T>({qualifier})` | A bean or `null` |
| `getBeans<T>({qualifier})` | Every bean of `T`, sorted by `@Order` |
| `value<T>(expression)`, `optionalValue<T>(expression)` | A `${...}` or `#{...}` expression resolved as a `@Value` field would be |
| `context`, `environment` | The running context and its environment |
| `mockMvc` | Requests to the controllers in memory (with the web starter); a `StateError` without it |
| `localServerPort` | The port of the real server (`randomPort`, `definedPort`); a `StateError` when none runs |
| `output` | The lines the application printed, such as the failure report of a context that did not start; also printed when a test fails |
| `markDirty()` | A new context for the next test |

```dart
test('reads its configuration', () {
  expect(app.value<int>(r'${shop.max-basket-size}'), 25);
  expect(app.environment.activeProfiles, ['test']);
  expect(app.getBeans<PaymentGateway>(), hasLength(1));
});
```

The startup information is logged through `SpringLog`, not printed, so it is not in `output`: use [captureLogs](captured-logs.md) for it.

## A context that does not start

When the application fails to start, the tests of the group fail with the error, and `app.output` holds the `APPLICATION FAILED TO START` report, which is also printed with the failure.

## Several applications

A package with several entry points has several generated files: pass the one you want (`admin.springApplication` with an import prefix). Test classes name it with `@SpringBootTest(application: 'bin/admin.dart')`; see [Test classes](test-classes.md).

## In Spring (Java)

```java
@SpringBootTest(args = "--shop.name=Night Books",
    properties = "logging.console.enabled=false")
@ActiveProfiles("test")
class CheckoutTest {
  @MockitoBean PaymentGateway gateway;
  @Autowired Checkout checkout;
}
```

The same options as annotations of a class. Here the function form is the base, and test classes are generated into it.

## See also

- [Test properties](test-properties.md)
- [Test classes](test-classes.md)
- [BeanOverride and @TestBean](bean-override.md)
- [MockMvc](mock-mvc.md)
