Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 37 ยท Strictness and Extensions

BDD Style and Lenient Stubbing

Write Mockito tests in given-when-then form with BDDMockito, learn when lenient stubbing is the right escape from strict stubs, and how to keep shared setup clean.

Two small features make Mockito tests easier to read and easier to keep strict: BDDMockito, which renames the API to match the given / when / then structure, and lenient stubbing, which lets a shared stub stay unused in some tests without breaking strictness. Both are about communication, not power: they do not add capabilities, they make intent visible.

Mockito does not run on this site, so real code is read-only. The runnable stand-ins show the idea of each feature in plain Java on top of the Mini library.

Given, when, then

A well-structured test has three parts:

  1. Given: the situation (stubs, objects).
  2. When: the action being tested.
  3. Then: the outcome (assertions and verifications).

Plain Mockito uses the word when for the given part, which collides with the when of the structure. BDDMockito gives the methods names that fit:

Classic BDDMockito
when(mock.m()).thenReturn(x) given(mock.m()).willReturn(x)
when(mock.m()).thenThrow(ex) given(mock.m()).willThrow(ex)
when(mock.m()).thenAnswer(a) given(mock.m()).willAnswer(a)
doReturn(x).when(mock).m() willReturn(x).given(mock).m()
doNothing().when(mock).m() willDoNothing().given(mock).m()
verify(mock).m() then(mock).should().m()
verify(mock, times(2)).m() then(mock).should(times(2)).m()
verifyNoInteractions(mock) then(mock).shouldHaveNoInteractions()

The real thing:

Java
import static org.mockito.BDDMockito.*;

@Test
void declinedCardIsNotSaved() {
    // given
    given(gateway.charge(any())).willReturn(false);

    // when
    String result = service.checkout(new Cart("book"));

    // then
    assertEquals("DECLINED", result);
    then(orders).should(never()).save(any());
    then(orders).shouldHaveNoInteractions();
}

BDDMockito extends Mockito, so one static import covers everything. Behavior is identical to the classic names; it is purely a style choice. Pick one style per project.

The idea in plain Java (stand-in)

You can see that BDD names are just renames by building them on Mini:

Java given / willReturn / then should: only renames

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

given(...) simply calls when(...). The real BDDMockito.given does the same, and returns a BDDMyOngoingStubbing with willReturn instead of thenReturn.

Lenient stubbing

Strict stubs fail a test for any stub it did not use. That is usually right. But consider a shared setup:

Java
@BeforeEach
void setUp() {
    when(config.currency()).thenReturn("EUR");    // used by most tests, not by all
    when(clock.instant()).thenReturn(NOW);
}

The tests that never reach config.currency() would fail with UnnecessaryStubbingException. You have three honest options:

  1. Move the stub into the tests that need it (usually best).
  2. Make this stub lenient, keeping strictness for everything else.
  3. Make the whole test class lenient (last resort).
Java
// Option 2: one stub is lenient
lenient().when(config.currency()).thenReturn("EUR");

// Same with BDD style
lenient().when(...)   // BDDMockito has no separate name; use lenient() with the classic call

// Mock-level: every stub on this mock is lenient
@Mock(strictness = Mock.Strictness.LENIENT) Config config;

// Class-level
@MockitoSettings(strictness = Strictness.LENIENT)

lenient() is deliberately visible in the code: a reviewer sees that this stub is allowed to be unused. It is the right tool for a default that most tests override or ignore, such as a happy-path setUp.

Lenient in the stand-in

The stand-in strict check from the last lessons can skip stubs that were marked lenient. The code below marks one stub lenient and reports only the rest:

Java A lenient stub is not reported

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Only taxPercent is reported. The currency stub is unused too, but it was declared lenient, so it is tolerated. Real Mockito does the same bookkeeping: lenient() marks that single stubbing.

Guidelines

  • Leniency is a documented exception, not a default. If more than a few stubs are lenient, the shared setup is too big.
  • A lenient stub must not hide a bug. Keep verify calls for behavior that must happen.
  • BDD style pays off most in longer tests with three clear blocks. In two-line tests the classic names are just as readable.
  • Mixing both styles in one project is confusing; agree on one in your team guidelines.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Which BDDMockito call corresponds to when(mock.m()).thenReturn(x)?

    BDDMockito.given(...).willReturn(...) is the renamed stubbing call. Behavior is identical.
  2. 2. What does lenient().when(...) do under strict stubs?

    Lenient applies to a single stubbing (or a mock or class if configured so), exempting it from the unused-stub check.
  3. 3. What is usually the best fix for a shared @BeforeEach stub that only some tests use?

    Narrowest scope first: move the stub, or use lenient() on the single default stub.

Summary

  • BDDMockito renames the API for given / when / then: given, willReturn, willThrow, then(mock).should().
  • It adds no new features; choose one style per project.
  • Strict stubs report unused stubs; lenient() exempts one stub, @Mock(strictness = ...) a mock, @MockitoSettings a class.
  • Prefer moving stubs to the tests that need them; use leniency for true shared defaults.

Next: Over-mocking and test smells