Testing Android Realm with RxJava - "open from thread without Looper" Exception

I have the following code based on the documentation provided by Realm ( https://realm.io/docs/java/latest/#rxjava )

public Observable<Foo> getFooById(String id) { realm = Realm.getInstance(realmConfiguration); return realm.where(Foo.class) .equalTo("id", id) .findFirstAsync() .asObservable() .filter(this::filterResult); } 

This works in the App as expected, however, when it comes to testing, things get a little more complicated. I have the following test (trimmed to make it simple):

 @Test public void testRealmExample() { RealmConfiguration config = new RealmConfiguration.Builder(context) .name("test.realm") .inMemory() .build(); DataManager dataManager = new DataManager(config); TestSubscriber<Foo> testSubscriber = new TestSubscriber<>(); dataManager.getFoo("").observeOn(AndroidSchedulers.mainThread()).subscribe(testSubscriber); testSubscriber.assertNoErrors(); } 

Error java.lang.IllegalStateException: Your Realm is opened from a thread without a Looper. Async queries need a Handler to send results of your query java.lang.IllegalStateException: Your Realm is opened from a thread without a Looper. Async queries need a Handler to send results of your query .

To counter this, I read on the Realm GitHub page that they use the @UiThreadTest annotation to make the test run in a user interface thread, which from my understanding is a looper thread, so this should solve my problem. I added:

 @Rule public final UiThreadTestRule uiThreadTestRule = new UiThreadTestRule(); 

and modified my test to include annotation

 @Test @UiThreadTest public void testRealmExample() { ...} 

This still gives the same exception. Does anyone know why and solution? Thanks.

+5
source share
1 answer

@UiThreadTest doesn't actually put you in a Looper workflow, just in a thread with access to user interface elements. I must admit, I really did not look into the details about why this difference exists. Instead, we use our own rule for Looper threads (which also clears our Realm instances). You can see it here and perhaps use it as inspiration:

https://github.com/realm/realm-java/blob/master/realm/realm-library/src/androidTest/java/io/realm/rule/RunInLooperThread.java

0
source

Source: https://habr.com/ru/post/1241804/


All Articles