0Pricing
Testing Mastery: JUnit, Mockito & Integration Tests · レッスン

例外のスローと連続呼び出し

モックを設定して例外をスローさせたり、連続した呼び出しごとに異なる値を返させたりし、より豊かなテストシナリオを作成します。

「例外のスローと連続呼び出し」はCoddyKit上の無料Testing Mastery: JUnit, Mockito & Integration Testsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはTesting Mastery: JUnit, Mockito & Integration Tests学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Testing Mastery: JUnit, Mockito & Integration Testsコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Beyond Simple Returns

Stubbing return values covers the happy path, but real code must also handle errors and changing state. Mockito lets you stub mocks to throw exceptions and to vary their answers per call.

thenThrow Basics

Use thenThrow to make a stubbed method raise an exception, so you can test your error handling.

when(repo.findById(99L))
    .thenThrow(new NotFoundException());

Testing the Failure Path

Combine the throwing stub with assertThrows to verify your code reacts correctly.

@Test
void propagatesError() {
  when(repo.findById(99L)).thenThrow(new NotFoundException());
  assertThrows(NotFoundException.class,
      () -> service.load(99L));
}

Throwing from void Methods

For void methods you cannot use when(...) directly. Use doThrow(...).when(mock).method() instead.

doThrow(new IllegalStateException())
    .when(logger).flush();

Consecutive Return Values

Pass multiple arguments to thenReturn to return different values on successive calls. The last value repeats once exhausted.

when(counter.next())
    .thenReturn(1, 2, 3);

Chaining Stub Calls

You can also chain calls. Each call describes the next invocation in order.

when(counter.next())
    .thenReturn(1)
    .thenReturn(2)
    .thenThrow(new IllegalStateException());

Mixing Returns and Throws

A common pattern: succeed a few times, then fail. This models flaky resources like a retrying network client.

when(client.fetch())
    .thenReturn("ok")
    .thenThrow(new IOException("down"));

Checked Exceptions Caveat

A mock can only throw a checked exception that the stubbed method declares. Throwing an undeclared checked exception causes a runtime error from Mockito.

doReturn for Consecutive Values

The do* family also supports chaining and is required when stubbing spies or void methods.

doReturn("a")
    .doReturn("b")
    .when(provider).value();

Why This Matters

Exception and consecutive stubbing let you exercise retry logic, fallback paths, and stateful sequences without building complex fake objects.

Putting It Together

You can now drive a mock through a full sequence of success and failure to validate resilient code.

when(api.call())
    .thenReturn("first")
    .thenThrow(new TimeoutException());

Quick Check

How do you make a stubbed method return 1, then 2 on its second call?

Recap

You learned advanced stubbing:

  • thenThrow / doThrow simulate errors
  • Multiple thenReturn args or chains give consecutive values
  • Mocks can only throw declared checked exceptions
  • Use do* for void methods and spies

よくある質問

「例外のスローと連続呼び出し」レッスンは無料ですか?

はい。「例外のスローと連続呼び出し」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Testing Mastery: JUnit, Mockito & Integration Testsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Testing Mastery: JUnit, Mockito & Integration Testsコースには全4レッスンが含まれています。

「例外のスローと連続呼び出し」で何を学びますか?

モックを設定して例外をスローさせたり、連続した呼び出しごとに異なる値を返させたりし、より豊かなテストシナリオを作成します。 ブラウザで直接実行するハンズオンコードでTesting Mastery: JUnit, Mockito & Integration Testsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Testing Mastery: JUnit, Mockito & Integration Testsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのTesting Mastery: JUnit, Mockito & Integration Testsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。

「例外のスローと連続呼び出し」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このTesting Mastery: JUnit, Mockito & Integration Testsレッスンでコードを書いて実行できますか?

はい。すべてのTesting Mastery: JUnit, Mockito & Integration Testsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. 戻り値のスタブ化
  2. MockitoのArgument Matcher
  3. 実オブジェクトをSpyする
  4. 例外のスローと連続呼び出し
← Testing Mastery: JUnit, Mockito & Integration Testsに戻る