为何Android类在单元测试中调用构造函数不抛出Stub!异常?
Android本地单元测试中Rect构造函数未抛出Stub!异常的原因探究
问题背景
Android本地单元测试(非插桩测试)运行在本地主机时,按文档说明会使用带桩实现的伪造android.jar。通过反编译工具查看其中的Rect.java类,可见其所有构造函数和方法都定义了抛出RuntimeException("Stub!")的逻辑,代码示例如下:
public final class Rect implements Parcelable { @NonNull public static final Parcelable.Creator<Rect> CREATOR = null; public int bottom; public int left; public int right; public int top; public Rect() { throw new RuntimeException("Stub!"); } public Rect(int left, int top, int right, int bottom) { throw new RuntimeException("Stub!"); } public Rect(@Nullable Rect r) { throw new RuntimeException("Stub!"); } public boolean equals(Object o) { throw new RuntimeException("Stub!"); } public int hashCode() { throw new RuntimeException("Stub!"); } public String toString() { throw new RuntimeException("Stub!"); } @NonNull public String toShortString() { throw new RuntimeException("Stub!"); } @NonNull public String flattenToString() { throw new RuntimeException("Stub!"); } //.... }
但实际测试中发现:调用Rect()构造函数时并未抛出该异常,仅调用类方法时才会抛出。后续进一步验证发现,使用Gradle配置运行测试时构造函数不抛异常,而使用Kotest配置时则会按预期抛出Stub!异常。
核心疑问
- 该现象的根本原因是什么?是反编译输出存在错误,还是构造函数实际未按代码定义抛出异常?
- 曾猜测可能存在需要构造函数正常工作的场景(比如作为基类、或适配Mockito等依赖继承的Mock库),但
Rect是final类,无法被继承,因此无法理解该场景的合理性。
内容的提问来源于stack exchange,提问作者nsk
相关产品推荐
相关产品推荐

