Android Java Room.inMemoryDatabaseBuilder for Instrumented tests using Espresso

27 Views Asked by At

I need help to use Room.inMemoryDatabaseBuilder for my Instrumented tests

In my Instrumented class I added this :

private MyDatabase database;

   @Rule

   public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule();

   @Before

   public void initDb() throws Exception {

      this.database = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(),

            MyDatabase .class)

            .allowMainThreadQueries()

            .build();

   }

   @After

   public void closeDb() throws Exception {

      database.close();

   }

But I get this error

Exception while computing database live data.

at androidx.room.RoomTrackingLiveData$1.run(RoomTrackingLiveData.java:92)

at androidx.room.TransactionExecutor$1.run(TransactionExecutor.java:47)

at androidx.arch.core.executor.testing.InstantTaskExecutorRule$1.executeOnDiskIO(InstantTaskExecutorRule

I do not find any example for the correct use in Instrumented test.

Actually the instrumented runs on the device's database and I need it to run with inMemoryDatabase. But the rest of the debug builds needs to still keep running on the device's database.

If anyone has an idea.

Thanks

Edit:

I found a solution but I don't know if it is the right way. In my database class I check to see if it contains an espresso class so that I know if we are in androidTest build :

    private static boolean isRunningAndroidTest() {
        try {
            Class.forName("androidx.test.espresso.Espresso");
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }

With this method I modified the creation of the database like this :

Builder<MyDatabase> builder;
        if (isRunningAndroidTest()) {
            // Use a different database configuration for testing if needed
            // For example, you might want to use an in-memory database for tests
            builder = Room.inMemoryDatabaseBuilder(application, MyDatabase.class)
                    .allowMainThreadQueries();
        } else {
            // Use the regular database configuration
            builder = Room.databaseBuilder(application, MyDatabase.class, DATABASE_NAME);
        }

Please correct me if there is a better way.

Thanks

0

There are 0 best solutions below