1

I'm trying to write some unit tests using spek framework, but keep running into RuntimeException (Method threw 'java.lang.RuntimeException exception. Stub!) when trying to access Looper (Looper.getMyLooper()) in code.

I'm using the TestScheduler provided by Rx as the Scheduler and tried @RunWith(AndroidJUnit4::class) as well as @RunWith(RobolectricTestRunner::class)

Any pointers?

Himanshu Chhabra
  • 257
  • 1
  • 2
  • 12

1 Answers1

1

Looper is Android dependency and you can't use it in unit tests. https://developer.android.com/studio/test#test_types_and_location

These are tests that run on your machine's local Java Virtual Machine (JVM). Use these tests to minimize execution time when your tests have no Android framework dependencies or when you can mock the Android framework dependencies.

Try to remove the explicit Looper dependency from the tested class and pass it from the outside (https://developer.android.com/training/dependency-injection) This is the best solution that leads to fast unit test and maintainable code.

Second option is rewrite you test to instrumented test and run it on Android emulator. This test will be slow.

Third option is setup Robolectric to mock Looper. Look at http://robolectric.org/javadoc/3.0/org/robolectric/shadows/ShadowLooper.html

ZSergei
  • 807
  • 10
  • 18