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
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 themainorgroup. It is closed withcloseAsync()in atearDownAllafter the last test, so asynchronous@PreDestroymethods 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.appis usable inside tests,setUp, and asetUpAlldeclared after thespringBootTestcall. Elsewhereapp.contextthrows aStateError, because the context does not exist yet.- The
SpringLoglevels and handler the application changed are restored after the last test. - Each
springBootTeststarts 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 |
ApplicationContextInitializers run before the refresh |
@ContextConfiguration(initializers) |
webEnvironment |
Which web server starts: mock (none, the default), randomPort, definedPort, none |
@SpringBootTest(webEnvironment) |
See Test properties for the precedence of the property options, BeanOverride for overrides and MockMvc 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 |
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 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.
In Spring (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.