FVod FVod - 2 months ago 27
Android Question

Testing method that uses realm

I have a Database data source that is using Realm. So now I want to test that class but I'm facing some problems about how to use fixtures and how to mock Realm.
My database data source looks like:

public class DatabaseDataSource {
private Realm realm;

public DatabaseDataSource(Realm realm) {
this.realm = realm;

public Observable<RealmResults> getContacts(String firstName, String lastName, String city, String zipCode) {

final RealmQuery realmQuery = realm.where(Contact.class);
if(!TextUtils.isEmpty(firstName)) {
realmQuery.contains("firstName", firstName);
if(!TextUtils.isEmpty(lastName)) {
realmQuery.contains("lastName", lastName));
if(!TextUtils.isEmpty(city)) {
realmQuery.contains("city", city);
if(!TextUtils.isEmpty(zipCode)) {
realmQuery.contains("zipCode", zipCode);

return realmQuery.findAll()

I'm using Robolectrics for other tests, and, in this case, I want to have a list of contacts in my mocked realm so I can check that filtering is working fine. How can I do that?
I've tried doing:

public class DatabaseDataSourceTest extends BaseTest {

private DatabaseDataSource databaseDataSource;

Realm realm;

public void setup() throws Exception {

Realm.setDefaultConfiguration(new RealmConfiguration.Builder().build());
realm = Realm.getDefaultInstance();

databaseDataSource = new DatabaseDataSource(realm);

public void getContacts_filterByName() {
databaseDataSource.getContacts("testName", null, null, null);
// I don't know what to do here


But I'm getting the following exception when doing: Realm.init(RuntimeEnvironment.application.getApplicationContext());

java.lang.UnsatisfiedLinkError: Can't load library: /var/folders/kc/76n8494x5cd2mtx340f27xch0000gn/T/android-tmp-robolectric409019390257818503/app_lib/librealm-jni.dylib

How should I do that?

Thanks in advance


: How to run Unit test in Realm Db using Roboelectric says, that Roboelectric is not supported yet, so you can't use unit testing, onlu instrumented tests on real android device. All tests are run on single thread, there is no need in rx in tests.