Skip to content
Ameen Abozaid
Planned lessonJNR-044-L02

Stubbing with Mockito

  • Lesson 2 of 6
  • Junior
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 @Mock and @InjectMocks sets 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

java
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.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.