0

Having an error when testing RxJava code. It fils when I call AndroidSchedulers.mainThread() in ViewModel. Does anyone know how to deal with it?

Here is my stack trace:

java.lang.ExceptionInInitializerError
    ...
    at com.cardsimulator.ui.MainViewModel.executeCommand(MainViewModel.java:56)
    at com.cardsimulator.ui.MainViewModelTest.testExecuteCommand_NormalCommand(MainViewModelTest.java:54)
    ...
Caused by: java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.

1 Answer 1

1

You should not use AndroidSchedulers.mainThead() for testing purpose. You can use Schedulers.trampoline() instead. It basically executes all the tasks on the current thread without any queueing and the timed overloads use blocking sleep as well.

You can use injection framework (as Dagger 2) for injecting the right scheduler. Or simply you can add this in your test:

@BeforeClass
public static void setupTest() {
    RxAndroidPlugins.setInitMainThreadSchedulerHandler(
            __ -> Schedulers.trampoline());
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.