
# BeanOverride and @TestBean

A bean that talks to something a test cannot use (a payment provider, the wall clock, a mail server) is replaced with an object of the test. The original definition is removed before any bean is created, so the real object, and whatever it would connect to, is never built. Every bean that injects it gets the replacement.

It is Spring's `@TestBean` and `@MockitoBean`, with a ready-made object instead of a generated mock.

## Why

A test that charges a real card or sends a real mail is slow, flaky and dangerous. Replacing one bean keeps the rest of the application real, so the test still checks the wiring, the properties and the controllers.

## Example

As a function:

```dart
final gateway = FakeGateway();
final clock = FixedClock(DateTime(2026, 1, 1));

final app = springBootTest(
  springApplication,
  overrides: [
    BeanOverride<PaymentGateway>(gateway),                  // the only bean of the type
    BeanOverride<Clock>(clock),
    BeanOverride<PaymentGateway>(MockGateway(), name: 'sandbox'), // one of several, by name
  ],
);
```

As a class:

```dart
@SpringBootTest()
class PaymentTest {
  @TestBean(name: 'sandbox')            // replaces the bean named sandbox
  final gateway = FakeGateway();

  @TestBean()                           // replaces the only Clock
  final Clock clock = FixedClock(DateTime(2026, 1, 1));

  @TestBean()                           // no Mailer bean: adds one
  final Mailer mailer = RecordingMailer();

  @Autowired()
  late Checkout checkout;

  @Test()
  void paysThroughTheFake() {
    checkout.pay(12.5);
    expect(gateway.charged, [12.5]);
  }
}
```

## Which bean is replaced

| Given | Replaces |
|---|---|
| `name:` | The bean of that name, or the bean that name is an alias of |
| no name | The only bean of `T`; among several, the single `@Primary` one. Several and no single primary fail the start with a `StateError` that lists them |
| no bean of `T` | Nothing: the instance is added as a new bean named after the type (`PaymentGateway` is `paymentGateway`) |

The replacement keeps the original's name, aliases, qualifiers, order and `@Primary` / `@Fallback` flags, so `@Qualifier` injection points still find it. When several overrides replace the same bean, the last one wins.

## Under which types

- **`BeanOverride<T>(instance)`** registers the replacement under `T` only. If the original was also found under another type (it implemented a second interface), that type no longer finds it.
- **`BeanOverride.named(instance, name: ...)`** keeps the original's types (except its own class) and adds `T` (unless it is `Object`) and the class of the instance. Give the fake's own types when it implements only some of the original's: `BeanOverride.named(fake, name: 'sandbox', types: [FakeGateway, PaymentGateway])`.
- **`@TestBean(name: ...)`** generates `BeanOverride.named`. When the field's value is created with a constructor (`= FakeGateway()`, also a named constructor or a cascade), the generated override lists that class and all its public supertypes. Any other value (`= Fakes.gateway()`) keeps the original's types.
- **`@TestBean()` without a name** generates `BeanOverride<Type>(value)` with the field's declared type, which must be written (`final Clock clock = ...`), or the build fails. `@TestBean(type: Clock)` names it explicitly.

## Things to know

- **Nothing is reset between tests.** The value is created once, with the test class or `main`. Reset shared fakes and mocks in `setUp` (`@BeforeEach`), or use `@DirtiesContext`.
- **Any fake or mock works**, for example from `package:mocktail`; the starter has no mocking library of its own (Spring ships Mockito).
- **A misspelt `name:` does not fail.** When no bean has that name, the instance is added under it and the real bean stays. The usual symptom is the real bean still being used, or an error about two beans of `T`.
- **Without `name:` and without a bean of `T`**, the instance is registered as `defaultBeanName(T)`; if an unrelated bean already has that name, that bean is removed.
- In an `ApplicationContextRunner`, `withBeanOverride<T>(instance)` does the same after the configurations were registered.

## In Spring (Java)

```java
@MockitoBean PaymentGateway gateway;              // a generated Mockito mock
@TestBean(name = "sandbox") PaymentGateway sandbox;
static PaymentGateway sandbox() { return new FakeGateway(); }
```

Differences: a ready-made object instead of generated mocks or spies, no `@MockitoBean(reset)`, and an override without an existing bean adds the instance instead of failing.

## See also

- [springBootTest](spring-boot-test.md)
- [Test classes](test-classes.md)
- [ApplicationContextRunner](application-context-runner.md)
