Stubbing with Mockito
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
make a mock return values or throw exceptions.
Planned topics
@ExtendWith(MockitoExtension.class)with@Mockand@InjectMockssets things up. Verify the current Mockito version before recording.when(mock.method(arg)).thenReturn(value)stubs a return.thenThrow(...)simulates failure, such as a timeout.- Unstubbed methods return defaults (null, 0, empty collections).
- Use argument matchers (
any(),eq()) sparingly, and if one argument uses a matcher, all must.
Draft outline details
Demonstration
when(gateway.charge(any(), eq(new BigDecimal("50.00"))))
.thenReturn(PaymentResult.approved("tx-1"));
when(gateway.charge(any(), eq(new BigDecimal("99.00"))))
.thenThrow(new GatewayTimeoutException());Check your understanding
What does an unstubbed method returning a List give?
Show answer
An empty list.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.