0Pricing
Testing Mastery: JUnit, Mockito & Integration Tests · 课时

抛出异常与连续调用

为模拟对象设置抛出异常的行为,并让它们在连续调用中返回不同的值,以覆盖更丰富的测试场景。

抛出异常与连续调用 是 CoddyKit 上的免费 Testing Mastery: JUnit, Mockito & Integration Tests 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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

常见问题解答

「抛出异常与连续调用」课时是免费的吗?

是的 — 「抛出异常与连续调用」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Testing Mastery: JUnit, Mockito & Integration Tests 课程的其余内容,请升级到 CoddyKit PRO。 Testing Mastery: JUnit, Mockito & Integration Tests 课程共包含 4 节课。

「抛出异常与连续调用」这节课中我会学到什么?

为模拟对象设置抛出异常的行为,并让它们在连续调用中返回不同的值,以覆盖更丰富的测试场景。 你通过在浏览器中直接运行的动手代码来练习 Testing Mastery: JUnit, Mockito & Integration Tests,全天候 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 参数匹配器
  3. 监视真实对象
  4. 抛出异常与连续调用
← 返回 Testing Mastery: JUnit, Mockito & Integration Tests