Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 37 ยท Mocks and Stubs

Stubbing Exceptions with thenThrow and doThrow

Make Mockito mocks throw exceptions with thenThrow and doThrow to test error handling, retries and fallbacks, including checked exceptions and void methods.

The happy path is easy to test. The code that decides what to do when something goes wrong (a timeout, a missing record, a rejected payment) is where bugs hide, and it is also the code you can hardly trigger with real collaborators. A mock can throw on demand. This lesson shows how to make a mock throw, how to do it for void methods, the rule about checked exceptions, and how to test fallbacks and retries with it.

Real Mockito lines are read-only; runnable examples use the Mini stand-in from What Is Mockito?, which implements thenThrow, doThrow and the checked-exception check described here.

thenThrow

Instead of thenReturn(value), finish the stubbing with thenThrow(exception):

Java
when(gateway.charge("card-1", 50)).thenThrow(new PaymentDeclinedException("insufficient funds"));

The next time the code under test calls gateway.charge("card-1", 50), the exception is thrown from inside the mock, exactly as a real gateway would throw it. You can also pass a class, thenThrow(IllegalStateException.class), and Mockito creates the exception without calling its constructor. An instance is usually better, because you control the message and can check it later.

The checked-exception rule

Mockito refuses to throw a checked exception that the method does not declare, because the real method could never throw it either. If charge is declared as void charge(...) throws PaymentDeclinedException, the stubbing above is allowed. If it is declared without throws, Mockito fails the stubbing with Checked exception is invalid for this method!. Unchecked exceptions (RuntimeException and Error subclasses) are always allowed.

Try it: fallback logic

The service below asks a primary exchange-rate provider, and falls back to a cached rate when the provider fails. You cannot cause a real provider to time out on request, but a mock can:

Java Testing a fallback with thenThrow

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.

Both branches of toEuro are now tested without a network. The GBP stub throws a checked exception, which is allowed because rate declares throws RateUnavailableException.

doThrow for void methods

when(mock.call()) needs a call that returns a value, because that value is what you pass to when. A void method has no value, so when(mailer.send(...)) does not compile. Mockito's second family of stubbing methods works the other way round: you describe the answer first and the mock second:

Java
doThrow(new MailServerDownException()).when(mailer).send(anyString(), anyString());

Read it as: "do throw this, when this mock gets that call". doThrow works for non-void methods too, and it is required in a few cases:

  • void methods, as shown above;
  • spies, where when(spy.call()) would run the real method during stubbing (see the Spies chapter);
  • stubbing the same method again on a mock that already has a throwing stub, where the setup call itself would throw.

Along with doThrow come doReturn(value).when(mock).call(), doNothing().when(mock).call() (for void methods) and doAnswer(...); all four are covered in Default Answers and Void Methods.

Try it: void methods and the checked rule

Java doThrow, and the checked-exception rule

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 first call prints true because the mock's send did nothing. After doThrow(...) the same call fails inside the mock and notifyUser returns false.

Testing retries with several answers

Combine thenThrow with thenReturn to simulate "fails twice, then succeeds" (the next lesson, Consecutive Stubbing and Answers, explains the chaining rules):

Java
when(client.fetch("/data"))
    .thenThrow(new IOException("reset"))
    .thenThrow(new IOException("reset"))
    .thenReturn("payload");

A retry loop that gives up after three attempts can then be tested without real time passing or a real flaky network.

Asserting that the exception escapes

When the code under test is supposed to propagate an exception, assert it with JUnit's assertThrows:

Java
@Test
void declinedCardIsReportedToTheCaller() {
    when(gateway.charge("card-1", 50)).thenThrow(new PaymentDeclinedException("declined"));

    PaymentDeclinedException e = assertThrows(PaymentDeclinedException.class,
        () -> checkout.pay("card-1", 50));

    assertEquals("declined", e.getMessage());
    verify(orders, never()).markPaid(anyString());      // nothing was recorded as paid
}

The last line is typical of error-path tests: not only did the exception come out, but the follow-up work did not happen. Verification is the topic of the next chapter.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can you not write when(mailer.send(to, text)).thenThrow(...) for a void method?

    when() receives the result of the call. For void methods use doThrow(...).when(mock).method(...).
  2. 2. What happens if you stub a checked exception that the method does not declare?

    Mockito validates that the exception could really be thrown by the method signature, and reports 'Checked exception is invalid for this method!'.
  3. 3. Which exceptions can always be thrown by a stub?

    Unchecked exceptions are allowed for every method; checked ones must be declared in the method's throws clause.
  4. 4. What is a good reason to stub a mock to throw?

    Error paths such as fallbacks, retries and cleanup are hard to trigger with real collaborators but easy with a throwing mock.

Summary

  • when(mock.call()).thenThrow(exception) makes a call throw; pass an instance to control message and cause.
  • Checked exceptions must be declared by the method, otherwise Mockito rejects the stubbing.
  • For void methods use doThrow(exception).when(mock).method(...).
  • Combine throws and returns to test fallbacks and retries.
  • Assert propagated exceptions with assertThrows, and verify that the follow-up work did not happen.

Next: Consecutive Stubbing and Answers