【问题标题】:RuntimeException Stub! in unit tests using spekRuntimeException 存根!在使用 spek 的单元测试中
【发布时间】:2020-09-22 14:46:18
【问题描述】:

我正在尝试使用 spek 框架编写一些单元测试,但在尝试访问代码中的 Looper (Looper.getMyLooper()) 时,一直遇到 RuntimeException (Method threw 'java.lang.RuntimeException exception. Stub!)。

我正在使用 Rx 提供的 TestScheduler 作为调度程序,并尝试了 @RunWith(AndroidJUnit4::class) 以及 @RunWith(RobolectricTestRunner::class)

任何指针?

【问题讨论】:

    标签: android unit-testing spek


    【解决方案1】:

    Looper 是 Android 依赖项,您不能在单元测试中使用它。 https://developer.android.com/studio/test#test_types_and_location

    这些是在您机器的本地 Java 虚拟机上运行的测试 (JVM)。当您的测试有 没有 Android 框架依赖项或何时可以模拟 Android 框架依赖。

    尝试从测试类中移除显式的 Looper 依赖并从外部传递它 (https://developer.android.com/training/dependency-injection) 这是导致快速单元测试和可维护代码的最佳解决方案。

    第二个选项是将您的测试重写为检测测试并在 Android 模拟器上运行它。这个测试会很慢。

    第三个选项是设置 Robolectric 来模拟 Looper。看http://robolectric.org/javadoc/3.0/org/robolectric/shadows/ShadowLooper.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-12
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 1970-01-01
      相关资源
      最近更新 更多