You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RxJava单元测试:thenReturn Single.error与thenThrow Exception的区别

问题描述

我正在为methodOne编写单元测试,尝试模拟异常场景。相关代码如下:

Single<String> methodOne() {
     methodTwo();
     return Single.just("Hello");
}

Single<String> methodTwo() {
//some network calls
return Single.just("World");
}

我发现有两种模拟异常的方式:

when(test.methodTwo()).thenReturn(Single.error(new BadRequestException("bad request")));
when(test.methodTwo()).thenThrow(new BadRequestException("bad request"));

请问这两种方式之间有什么区别?

区别解析

这两种写法的核心差异在于异常触发的时机和机制完全不同:

  • thenReturn(Single.error(...))
    这种方式是让methodTwo()正常返回一个RxJava的Single对象,只是这个对象内部携带了错误信号。只有当你订阅这个返回的Single时,才会触发onError回调,整个调用过程完全符合RxJava的异步错误处理逻辑。
    比如在你的代码里,methodOne只是调用了methodTwo()但没有订阅它的返回值,那这个错误信号不会被触发,methodOne依然会正常返回Single.just("Hello")。

  • thenThrow(...)
    这种方式是让methodTwo()在被调用的瞬间同步抛出异常,相当于methodTwo的执行逻辑直接崩溃,完全跳过了返回Single的流程。这个异常会直接进入Java的同步异常处理流程,会立即打断当前的执行线程——比如你的methodOne在调用methodTwo()时会直接抛出这个异常,根本不会走到返回Single.just("Hello")的步骤。

简单来说:前者是返回一个"带错误的RxJava流",后者是直接在调用方法时同步抛错,两者的错误处理路径完全不一样。

内容的提问来源于stack exchange,提问作者rangarok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 04:01:07