'Room Upsert Test Loading Infinitely

I'm trying to add an upsert (insert or update) function with Room DB. I found an existing implementation and added it to my DAO. However, my androidTests for this upsert function end up running infinitely. Using OnConflictStrategy.REPLACE with my insert() function isn't an option for me because I'm using foreign keys. This is explained well here.

My DAO:

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun insertFolder(folder: Folder): Long

    @Update
    suspend fun updateFolder(folder: Folder)

    @Transaction
    suspend fun upsert(folder: Folder) {
      Log.d("some_tag", "upsert") // never shows up in logcat
      val id = insertFolder(folder)
      if (id == -1L) {
          updateFolder(folder)
      }
    }

My Test Class:

@ExperimentalCoroutinesApi
@RunWith(AndroidJUnit4::class)
@SmallTest
class FolderDaoTest {

    @get:Rule
    var instantTaskExecutorRule = InstantTaskExecutorRule()

    private lateinit var folderDao: FolderDao
    private lateinit var novelDao: NovelDao
    private lateinit var database: LibraryDatabase

    @Before
    fun setup() {
        database = Room.inMemoryDatabaseBuilder(
            ApplicationProvider.getApplicationContext(),
            LibraryDatabase::class.java
        ).allowMainThreadQueries().build()

        folderDao = database.folderDao
        novelDao = database.novelDao
    }

    @After
    fun tearDown() {
        database.close()
    }

    @Test
    fun upsertAddsFolder() = runBlockingTest {
        Log.d("some_tag", "test start") //shows in logcat
        val folder = Folder(id = 1, title = "abc")
        folderDao.upsert(folder) //gets stuck here infinitely
        
        Log.d("some_tag", "after upsert") // doesn't show up in logcat

        val allFolders = folderDao.getFolders().getOrAwaitValue()
        assertThat(allFolders).containsExactly(folder)
    }

}

My insert() and update() DAO functions work fine. I have functional tests for those. What's strange is that my log statement in the upsert function never shows up.

My version of coroutines-test is 1.5.2 but I also tried updating to 1.6.0 and using scope.runTest {} instead of runBlockingTest {}. I have also tried runBlocking {}.The results didn't change for any of these methods.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source