ApplicationContextRunner

ApplicationContextRunner starts a small, throwaway context per test, to check what an auto-configuration creates under which properties and beans. It is the tool for starter authors, and Spring Boot's runner of the same name.

Why

A starter's auto-configuration must react to its surroundings: create a bean by default, back off when the application declares its own, change with a property, fail on a bad value. Starting a whole application for each case would be slow and would read its config files. The runner starts only the modules you give it, with the properties you give it.

Example

import 'package:neon_cache/spring_auto_configuration.dart';
import 'package:spring_boot_starter_test/spring_boot_starter_test.dart';
import 'package:test/test.dart';

void main() {
  final runner = const ApplicationContextRunner()
      .withAutoConfiguration(neonCacheAutoConfiguration);

  test('creates a cache by default', () {
    runner.run((context) {
      expect(context, hasSingleBean<Cache>());
    });
  });

  test('backs off for the application cache', () {
    // The application's own Cache, registered before the auto-configuration.
    runner.withBean<Cache>(AppCache.new).run((context) {
      expect(context, hasSingleBean<Cache>()); // a missing back-off gives two
      expect(context.getBean<Cache>(), isA<AppCache>());
    });
  });

  test('can be switched off', () {
    runner.withPropertyValues(['neon.cache.enabled=false']).run((context) {
      expect(context, doesNotHaveBean<Cache>());
    });
  });

  test('rejects a negative size', () {
    runner.withPropertyValues(['neon.cache.size=-1']).run((context) {
      expect(context, hasFailed(isA<BeanCreationException>()));
    });
  });
}

The methods

The runner is immutable: each with... method returns a new runner, so a base runner can be shared and extended in each test.

Method What it does
withAutoConfiguration(module, [metadata]) Adds an auto-configuration module under test. Pass its @AutoConfigurationModule as metadata when it has an order, before or after: Dart cannot read the annotation of a variable at run time. The modules are sorted as Spring Boot sorts them, whatever order they were added in
withUserConfiguration(module) Adds an application module, registered before the auto-configuration, so its beans are seen by the conditions
withBean<T>(supplier, name:) Registers a bean before the configurations; every run gets a new instance. A @ConditionalOnMissingBean backs off; a missing back-off shows up as a second bean, or as a failed start when the names clash. It never replaces a bean
withBeanOverride<T>(instance, name:) Replaces a bean after the configurations were registered, like a BeanOverride. It hides back-off mistakes: use withBean to test back-offs
withPropertyValues(['a=b', 'c: d', 'flag']) Properties as key=value or key:value, split at the first = or : and trimmed; no separator gives an empty value. They win over every other source
withSystemEnvironment({...}) Environment variables, added to those of earlier calls (NEON_CACHE_SIZE for neon.cache.size)
withInitializer(initializer) An ApplicationContextInitializer called before the refresh; in the order added (their order is not used)
withParent(context) A parent context, for a starter that runs in a child context
withAllowBeanDefinitionOverriding(bool) Lets a definition replace another of the same name; off by default
withAllowCircularReferences(bool) false is the default and the only working value; true fails every run with an UnsupportedError

What the runner does not do:

@ConfigurationProperties beans are bound and relaxed names work, as in an application.

run and runAsync

run(body) passes an AssertableApplicationContext to the body and closes the context with close() when the body returns. For a body that awaits, use runAsync: the context is refreshed with refreshAsync() and closed with closeAsync() once the returned future completes. With run, the context would be closed at the body's first await.

test('calls the client', () async {
  await runner.runAsync((context) async {
    expect(await context.getBean<CatalogClient>().find('1'), isNotNull);
  });
});

AssertableApplicationContext

A context that failed to start is passed too, instead of throwing, so a test can check that a configuration rejects bad input.

Member Meaning
startupFailure The error that stopped the start; null when it started
hasFailed Whether the context failed to start
context The started context; a StateError with the failure when it did not start
environment The environment, also after a failed start
getBean<T>({qualifier}), getBeanByName(name) A bean; throws when none matches or the context did not start
getBeanNamesForType<T>() The names of the beans of T in this context, not its parent
containsBean(name) Whether a bean of that name exists, here or in a parent

Matchers

Matcher Passes when the context has
hasSingleBean<T>() Exactly one bean of T
hasBean<T>() At least one bean of T
doesNotHaveBean<T>() No bean of T
hasBeanNamed('name') A bean with that name or alias
hasFailed([matcher]) Failed to start (an AssertableApplicationContext only); with a matcher, the error must match it

They accept the context of ApplicationContextRunner, a springBootTest handle, or any ListableBeanFactory such as an application context. On failure they list the beans found, or the reason the context did not start. As in AssertJ, beans of parent contexts count too.

In Spring (Java)

new ApplicationContextRunner()
    .withConfiguration(AutoConfigurations.of(NeonCacheAutoConfiguration.class))
    .withBean(Cache.class, AppCache::new)
    .withPropertyValues("neon.cache.size=-1")
    .run(context -> assertThat(context).hasFailed());

Differences: withAutoConfiguration(module, metadata) takes the module's annotation by hand; withBean<T>(supplier) takes the type as a type argument and a supplier; withBeanOverride and withSystemEnvironment have no Boot counterpart; matchers replace AssertJ's assertThat(context).

See also