skip to content

BDDMockito Style

BDDMockito renames the same machinery into given/willReturn and then().should() so tests read as given-when-then. Interviewers check that you know it is an alias layer — same engine, different verbs — and when a team standardizes on it.

on this pageshow

questions

4

Mockito ships a BDDMockito class offering given(...).willReturn(...). How does that relate to the classic when(...).thenReturn(...) stubbing API, and why would a team choose it?

level: juniorimportance: should knowfreq 40%

answer

  1. alias facade, same engine
  2. given/willReturn == when/thenReturn
  3. BDDMockito extends Mockito — one static import
  4. then(mock).should(...) == verify
  5. Kotlin: when is a keyword

basics

~20 s

BDDMockito is an alias facade over the same engine. given(mock.call()).willReturn(x) creates exactly the same stubbing as when(mock.call()).thenReturn(x); there is no behavioural difference. Teams use it so tests read given / when / then, reserving the word 'when' for the action under test.

solid answer

~40 s

`BDDMockito` adds no capability — it is a naming facade. `given(service.find(1)).willReturn(result)` produces the same stubbing as `when(service.find(1)).thenReturn(result)`, and the class extends `Mockito`, so a single static import of `org.mockito.BDDMockito.*` gives you `given` and `then` plus `mock`, `verify`, `times`, `any` and the rest. The motivation is readability under given/when/then. In classic Mockito, `when(...)` sets up a precondition, which clashes with the 'when' of the scenario — the action being tested. BDD naming puts setup under `given`, leaves the act line as plain code, and puts verification under `then(mock).should(...)`. The verbs mirror the classic ones: `willReturn`, `willThrow`, `willAnswer`, `willCallRealMethod`, plus the argument-last forms `willDoNothing().given(spy).method()` for void methods and spies. In Kotlin there is a practical reason too: `when` is a language keyword needing backticks, so `given` simply reads better.

code

java · 9 lines
java
// classic
when(rates.rate("EUR", "USD")).thenReturn(new BigDecimal("1.10"));
Money converted = service.convert(Money.of("100", "EUR"), "USD");
verify(rates).rate("EUR", "USD");

// BDD
given(rates.rate("EUR", "USD")).willReturn(new BigDecimal("1.10"));
Money converted = service.convert(Money.of("100", "EUR"), "USD");
then(rates).should().rate("EUR", "USD");

go deeper

for a junior

State that it is naming only and give the direct mapping given/willReturn to when/thenReturn, plus then(mock).should for verification.

for a middle

Add that BDDMockito extends Mockito so one static import suffices, and mention the argument-last forms for void methods and spies.

for a senior

Discuss it as a team convention: consistency, the readability payoff of freeing the word 'when' for the action, and the Kotlin keyword angle.

for a principal

Keep it proportionate — a style decision worth standardising and automating, with no behavioural implications to weigh.

## What BDDMockito is `org.mockito.BDDMockito` is a class of static methods that renames the standard Mockito API in behaviour-driven terms. It extends `Mockito`, so everything the core API offers is available through it as well. Nothing new happens at runtime: `given(...)` delegates to the same stubbing machinery as `when(...)`, and the resulting mock behaves identically. ## The mapping - `when(mock.call()).thenReturn(v)` becomes `given(mock.call()).willReturn(v)` - `thenThrow(e)` becomes `willThrow(e)` - `thenAnswer(a)` becomes `willAnswer(a)`, also spelled `will(a)` - `thenCallRealMethod()` becomes `willCallRealMethod()` - `doReturn(v).when(mock).call()` becomes `willReturn(v).given(mock).call()` - `doNothing().when(spy).call()` becomes `willDoNothing().given(spy).call()` - `verify(mock, times(2)).call()` becomes `then(mock).should(times(2)).call()` Consecutive stubbing chains the same way: `given(it.next()).willReturn(1).willReturn(2)`, or `willReturn(1, 2)`. ## Why the naming exists Behaviour-driven development structures a test as given (the world before), when (the single action), then (the expected outcome). Classic Mockito occupies the word `when` for stubbing, which is setup — the 'given' part. A test in the classic API therefore reads: when, when, when, call, verify. With BDDMockito it reads: given, given, call, then. The action line, the point of the test, stands alone with no Mockito verb wrapped around it. That is the whole benefit, and it is real but modest: communication, not power. Teams that already structure tests with `// given / // when / // then` comments usually adopt it so the code matches the comments. ## Practical notes One static import covers everything because of the inheritance: `import static org.mockito.BDDMockito.*;` yields `given`, `then`, `willReturn`, plus `mock`, `spy`, `verify`, `never`, `any`, `eq` and so on. There is no need to import `Mockito.*` alongside it. Because `given(mock.call())` invokes the method to record the stubbing, it carries the same constraint as `when(...)`: it cannot be used for void methods, and on a spy it would execute the real method. Those cases use the argument-last forms — `willThrow(...).given(mock).voidCall()` and `willDoNothing().given(spy).voidCall()`. Stubbing semantics are otherwise unchanged: argument matchers work the same, matchers must be used for all arguments or none, unused stubbings are still reported under strict stubbing, and stubbing the same call twice still overrides the earlier answer. In Kotlin, `when` is a reserved keyword and must be written with backticks, which is ugly enough that Kotlin projects commonly prefer `given` or a wrapper such as `whenever`. A small but genuine adoption driver. ## Common misunderstanding Candidates sometimes claim BDDMockito verifies behaviour more strictly, or that it is required by a BDD framework such as Cucumber. Neither is true: it is naming only, independent of any runner or specification framework, and perfectly usable with plain JUnit. The corollary is that mixing both styles in one class compiles fine but reads badly — pick one per project.

  • Does using BDDMockito change how strict stubbing or argument matchers behave?
    No. It is the same stubbing engine under different names, so matcher rules, the all-or-none matcher constraint, override semantics and strictness reporting are identical. An unused given(...) is reported exactly like an unused when(...).
  • Do you need both static imports, Mockito and BDDMockito?
    No, one is enough. BDDMockito extends Mockito, so importing org.mockito.BDDMockito.* statically also brings mock, spy, verify, times, never and the argument matchers into scope. Importing both only creates duplicate-name noise.

saying these in an interview costs you the question

  • Claiming BDDMockito is a different mocking engine or stricter than the classic API
  • Thinking it requires Cucumber, JBehave or some BDD runner
  • Believing given(...) can stub void methods like a value-returning call
  • Importing both Mockito.* and BDDMockito.* because 'verify is not in BDDMockito'
  • Saying it improves test isolation or correctness rather than readability

context

open as a page

In Mockito's BDD API, how do you assert that a collaborator was called a given number of times, never called, or called in a specific order, and how do those forms map to verify(...)?

level: middleimportance: should knowfreq 30%

basics

~10 s

Use then(mock).should(times(2)).save(order), then(mock).should(never()).charge(any()), then(mock).shouldHaveNoInteractions() and then(mock).shouldHaveNoMoreInteractions(). Ordering passes an InOrder object: then(mock).should(inOrder).lock(id). These are exact renamings of verify(mock, times(2)), verify(mock, never()) and verifyNoInteractions.

open as a page

Using Mockito's BDD API, how do you stub a method that returns void, or any method on a spy, and why can that call not be written in the same order as a normal value-returning stubbing?

level: middleimportance: should knowfreq 34%

basics

~20 s

Use the argument-last form: willDoNothing().given(spy).reindex(); willThrow(new IllegalStateException()).given(mailer).send(msg). A void call cannot be passed as an argument to given(...), and on a spy given(spy.call()) would run the real method first. The behaviour is stated before the call is recorded.

open as a page

A Java codebase mixes Mockito's classic when/verify calls and its BDD given/then calls inside the same test classes. What practical problems does that create, and how would you settle a convention for the team?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

Nothing breaks technically, but readers lose the given/when/then rhythm, reviews re-argue style per file, and Mockito's static then(...) collides with AssertJ's then(...). Pick one style, enforce it with an import rule in the linter or an architecture test, and migrate opportunistically rather than in a mass rewrite.

open as a page