Using Java Mockito with BDD Style Given-When-Then
Mockito unit tests tend to grow in a predictable shape: a block of stubbing, one call into the class under test, and a short list of assertions. That arrangement works, but it reads like plumbing rather than a description of behaviour. Plenty of Java teams in Sydney and Melbourne now phrase their unit tests in Given-When-Then form so that the test name, the setup and the expectation all use the same vocabulary that testers, developers and product owners already write into a Jira ticket or a Gherkin feature file.
BDDMockito is the part of Mockito that supports this style without dragging in another library. It gives you given(...).willReturn(...) in place of when(...).thenReturn(...), and then(mock).should() in place of verify(mock), while every mock, matcher, captor and annotation stays exactly where it was. The following walkthrough covers a working Maven setup, translating a written specification into executable mock interactions, a side-by-side of the two dialects, and the strictness traps that push teams back to the old habits after a week.
Why given-when-then suits Java unit tests
The classic arrange-act-assert pattern and Given-When-Then describe the same three phases, but the BDD wording carries intent. A given states a precondition in business terms, such as a quote request for next-day delivery to a New South Wales address. A when describes the single interaction that triggers the behaviour, and a then states the observable outcome. That vocabulary scales down from acceptance criteria to unit tests without a translation step, which matters when the person writing the acceptance criteria and the person maintaining the service are in different time zones.
A useful rule is that each when block should contain one behaviour. If a test needs two when sections, it usually covers two cases and should be split, because a failure message then points at one scenario instead of a list of suspects. This style also forces explicit statements about which collaborators were used. A mock that was never touched can be asserted with then(repository).shouldHaveNoInteractions(), which catches accidental coupling to a database that should not have been involved.
For teams working on Australian products, the vocabulary pays off quickly in the details. A checkout service for a local retailer has to handle GST on AUD amounts, shipping quotes keyed to postcodes like 2000 for Sydney or 4000 for Brisbane, and refund paths governed by the Australian Consumer Law. When those rules live in acceptance criteria written by analysts, the unit tests can mirror the same sentences rather than exposing BigDecimal scale arguments and mapper calls.
Setting up the project and dependencies
Mockito 5.x requires Java 11 or newer, and the BDD API ships inside mockito-core, so there is nothing exotic to install. The cleanest starting point is the JUnit 5 extension artifact, which pulls in mockito-core transitively and gives you strict stub checking by default.
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.11.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.14.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.26.3</version>
<scope>test</scope>
</dependency>
The class then needs @ExtendWith(MockitoExtension.class) at the top, with @Mock for collaborators and @InjectMocks for the class under test. The extension reports unused stubbings as failures at the end of the test, which is the single biggest quality gain for teams moving from manual mock creation. If you also use Spring Boot, keep the Spring-specific @MockBean for slice tests and use plain Mockito here, since the two lifecycles do not play well together.
Groovy and Spock deserve a mention because the vocabulary is native there. A Spock specification already uses given, when and then blocks, and its Mock() and Stub() objects map cleanly onto Java test doubles. Many Australian banks and fintechs in Melbourne and Sydney keep a polyglot build where Spock covers the specification-heavy behaviour suites and Mockito covers Java modules and shared test-support libraries, so learning the BDD dialect of Mockito pays off twice.
Translating a specification into mock interactions
Here is a complete example. The specification reads: given a carrier gateway that returns a next-day quote of $25.00, when a customer requests next-day shipping to Sydney, then the quote is returned and no repository write happens.
@ExtendWith(MockitoExtension.class)
class ShippingQuoteSpec {
@Mock
CarrierGateway carrierGateway;
@Mock
QuoteRepository quoteRepository;
@InjectMocks
ShippingQuoteService quoteService;
@Test
void quotesTwentyFiveDollarsForNextDayDelivery() {
given(carrierGateway.quote(any(ShippingAddress.class), eq(ShippingSpeed.NEXT_DAY)))
.willReturn(new Quote("AUS-4821", new BigDecimal("25.00")));
Quote quote = quoteService.quote(
new ShippingAddress("Sydney", "NSW", 2000),
ShippingSpeed.NEXT_DAY);
assertThat(quote.amount()).isEqualByComparingTo("25.00");
assertThat(quote.reference()).isEqualTo("AUS-4821");
then(carrierGateway).should()
.quote(any(ShippingAddress.class), eq(ShippingSpeed.NEXT_DAY));
then(quoteRepository).shouldHaveNoInteractions();
}
}
The given block is the only place where stubbing happens, and it reads top to bottom as a precondition. Matchers behave exactly as before: any(ShippingAddress.class) for a collaborator you do not care about, eq(...) for a value the behaviour depends on. The call into quoteService is the when phase even though no keyword is needed, and the assertions plus then(...).should() form the then phase.
Failures and interactions have their own helpers. given(gateway.quote(...)).willThrow(new CarrierUnavailableException("carrier down")) covers error paths, willAnswer(...) computes a return value from the invocation arguments, and then(mock).shouldNot().method(...) asserts an absence. When order matters, InOrder still works with the BDD API: create the in-order instance as usual and call then(gateway).should(inOrder).method(...). For payloads that are hard to compare, an ArgumentCaptor remains the pragmatic choice rather than hand-rolling equals methods on request objects.
Comparing the classic and BDD dialects
Both styles come from the same library, so the differences are about readability rather than capability.
| Aspect | Classic Mockito | BDD Mockito |
|---|---|---|
| Stubbing | when(mock.method()).thenReturn(value) |
given(mock.method()).willReturn(value) |
| Throwing | when(mock.method()).thenThrow(error) |
given(mock.method()).willThrow(error) |
| Verification | verify(mock).method(args) |
then(mock).should().method(args) |
| Unused interactions | verifyNoMoreInteractions(mock) |
then(mock).shouldHaveNoMoreInteractions() |
| Ordered checks | inOrder.verify(mock).method() |
then(mock).should(inOrder).method() |
| Natural reading | Arrange, act, assert | Given, when, then |
Migrating an existing suite is mostly a matter of swapping static imports and renaming call sites, which makes it easy to run a mixed codebase during the transition. One asymmetry to remember is that BDDMockito.then accepts a mock, while AssertJ ships its own Assertions.then for readable condition names, and importing both statically fails to compile. The habit worth forming is to use assertThat(...) for values and then(mock) for collaborators, or to fully qualify BDDMockito.then(...) in the few places where both appear.
The bigger decision is where the style lives. A repository-wide rewrite of thousands of green tests buys very little, while converting the newest or the flakiest suites pays off immediately. In my experience the tests that benefit most are the ones with long setup blocks, because the given section isolates the state and the then section becomes a checklist of observable outcomes.
Pitfalls that make readable specs fall apart
Strict stubbing is the first source of friction. Mockito’s default STRICT_STUBS mode fails a test with UnnecessaryStubbingException when a stub is never used, which is exactly what you want, except when the stub sits in a branch that the current data does not reach. The fix is to move the stub into the branch that needs it rather than reaching for lenient(), and to reserve lenient mode for genuinely optional collaborators.
Over-mocking is the second. Mocking your own value objects and simple mappers turns the specification into a recording of implementation calls, and the test breaks every time the class is refactored. Mock boundaries such as HTTP clients, payment gateways and message producers, and prefer small hand-written fakes for in-memory repositories. If a test needs five mocks to describe one sentence, the unit is probably too small.
Time and data need local attention. Teams spread across Sydney, Melbourne, Adelaide and Perth hit daylight saving differences for half the year, and tests that call LocalDateTime.now() produce failures that only appear in one region. Inject a Clock and stub it instead. The same caution applies to test data: pull real customer records into a fixture and you inherit obligations under the Privacy Act 1988 and the 2024 online privacy reforms overseen by the OAIC, plus the Australian Consumer Law for anything customer-facing. Generate data with Datafaker using an en-AU locale for ABNs, phone formats and postcodes, and reach for WireMock when the contract under test is a REST API rather than a method call.
Moving a real suite across
The value of the BDD dialect is not the syntax but the conversation it enables. A test that reads as given a carrier returns a quote, when a customer requests next-day delivery, then the amount is $25.00 can be read aloud by a tester in Brisbane and a developer in Perth without translation, and the failure messages point at a behaviour instead of a line number.
A concrete next step: pick the single most brittle test in your module, rewrite it this week using given, willReturn and then(mock).should(), keep the existing assertions unchanged, and run it in your pipeline to confirm the strict-stubs report and the PIT mutation score before you convert anything else.