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:

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:

@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

Things to know

In Spring (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