Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 37 ยท Projects and Practice

Project: Payment Retry with Backoff

Test a retry mechanism without sleeping: consecutive stubbing with thenThrow then thenReturn, an injected Sleeper, permanent versus transient errors, and exact call counts.

Retry logic is hard to test the naive way: you would need a flaky service and real waiting. With test doubles it is easy and instant. In this project you test a RetryingPayments class that calls a gateway up to three times, waits 100 ms, then 200 ms between attempts (exponential backoff), and gives up immediately on a permanent error such as an invalid card.

The skills practiced here: consecutive stubbing (fail, fail, then succeed), an injected Sleeper so no real sleeping happens, precise verify(..., times(n)) counts, and InOrder-style reasoning. Mockito does not run on this site, so the runnable suite uses the labelled Mini stand-in; the real Mockito calls are shown beside it.

Specification

flowchart TD
  A["charge(card, cents)"] --> B["attempt 1"]
  B -->|"success"| OK["return receipt"]
  B -->|"TransientException"| W1["sleep 100 ms"]
  W1 --> C["attempt 2"]
  C -->|"success"| OK
  C -->|"TransientException"| W2["sleep 200 ms"]
  W2 --> D["attempt 3"]
  D -->|"success"| OK
  D -->|"TransientException"| X["throw PaymentFailedException"]
  B -->|"PermanentException"| P["throw immediately, no sleep"]

Transient failures are retried with growing delays; permanent failures are not retried.

  • TransientException (network trouble, timeout): retry, at most 3 attempts in total.
  • PermanentException (invalid card, insufficient funds): fail at once.
  • Delays: before the second attempt 100 ms, before the third 200 ms.
  • After the third failed attempt: throw PaymentFailedException.

The sleeper seam

If the class called Thread.sleep(...) directly, a test of the third-attempt path would wait 300 ms, and a test of ten retries would wait seconds. Putting waiting behind an interface fixes that:

Java
interface Sleeper { void sleep(long millis); }

Production passes Thread::sleep-based code; tests pass a mock (to verify delays) or a no-op.

Consecutive stubbing

Real Mockito lets you list consecutive results in one stub:

Java
when(gateway.charge("4111", 1500))
        .thenThrow(new TransientException("timeout"))
        .thenThrow(new TransientException("timeout"))
        .thenReturn("receipt-1");

The first call throws, the second throws, the third and every later call return receipt-1 (the last answer repeats). doReturn/doThrow chains work the same way for spies and void methods. The stand-in below has a tiny helper, outcomes(...), built on thenAnswer and a counter.

Code and tests

Java Retry class with six tests

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.

The whole file runs without waiting a single millisecond, even though the scenarios model 300 ms of backoff. The verify lines on the sleeper prove the schedule: exactly one wait of 100 and one wait of 200 for the "two failures" scenario, and none at all when the first attempt works.

Real Mockito version

Java
@ExtendWith(MockitoExtension.class)
class RetryingPaymentsTest {

    @Mock Gateway gateway;
    @Mock Sleeper sleeper;
    @InjectMocks RetryingPayments payments;

    @Test
    void twoTransientFailuresThenSuccess() {
        when(gateway.charge("4111", 1500))
                .thenThrow(new TransientException("timeout"))
                .thenThrow(new TransientException("timeout"))
                .thenReturn("receipt-3");

        assertEquals("receipt-3", payments.charge("4111", 1500));

        verify(gateway, times(3)).charge("4111", 1500);
        InOrder order = inOrder(sleeper);
        order.verify(sleeper).sleep(100);
        order.verify(sleeper).sleep(200);
        verifyNoMoreInteractions(sleeper);
    }

    @Test
    void permanentFailureIsNotRetried() {
        when(gateway.charge(any(), anyInt())).thenThrow(new PermanentException("invalid card"));

        assertThrows(PermanentException.class, () -> payments.charge("0000", 1500));

        verify(gateway, times(1)).charge("0000", 1500);
        verifyNoInteractions(sleeper);
    }
}

Two details: InOrder checks that the delays happened in sequence (100 before 200), which count-only checks cannot; and assertThrows (JUnit) captures the exception, so you can still verify the mocks afterwards.

Bonus: capturing delays instead of verifying each

When there are many retries it is easier to record the delays and assert on the list. A tiny fake does it:

Java A recording sleeper as a fake

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.

In real Mockito the equivalent is an ArgumentCaptor<Long> on sleeper.sleep(...) and assertEquals(List.of(100L, 200L), captor.getAllValues()).

Extension ideas

  1. Add jitter: the delay is randomized. Inject a Random or a DoubleSupplier to keep tests deterministic.
  2. Add a circuit breaker: after five consecutive failures the next call fails fast without contacting the gateway; test it with verifyNoInteractions(gateway).
  3. Make the attempt count and delays configurable and use a parameterized test over several configurations.
  4. Test a total timeout with a mutable Clock (see Mocking constructors and time).

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. What does when(g.charge(x)).thenThrow(a).thenThrow(a).thenReturn(r) mean for the fourth call?

    Consecutive answers are used in order and the last one is repeated for every later call.
  2. 2. Why is a Sleeper interface injected instead of calling Thread.sleep directly?

    The seam removes real waiting from tests and makes the backoff schedule observable.
  3. 3. Which tool proves that the 100 ms wait happened before the 200 ms wait?

    Count checks cannot see order. InOrder verifies the sequence of calls.

Summary

  • Consecutive stubbing (thenThrow(...).thenReturn(...)) models flaky dependencies in a few lines; the last answer repeats.
  • Inject waiting (Sleeper) so tests are instant and delays can be verified or captured.
  • Test the boundary counts: success on the first, second and third attempt, and giving up.
  • Distinguish transient from permanent errors and assert that permanent ones are not retried.
  • Use InOrder when order matters and verifyNoInteractions for the paths that must be silent.

Next: Practice: Mockito exercises