Skip to content

Instantly share code, notes, and snippets.

@madlymad
Last active March 24, 2021 14:33
Show Gist options
  • Save madlymad/08bd5c239d3211193398f19941e828bf to your computer and use it in GitHub Desktop.
Save madlymad/08bd5c239d3211193398f19941e828bf to your computer and use it in GitHub Desktop.
RoomDB testing
abstract class BaseTest {
@OptIn(ExperimentalCoroutinesApi::class)
@get:Rule
var coroutinesTestRule = CoroutinesTestRule()
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
lateinit var application: Application
lateinit var database: MyDatabase
@Before
open fun setUp() {
application = ApplicationProvider.getApplicationContext()
database = Room.inMemoryDatabaseBuilder(application, MyDatabase::class.java)
.fallbackToDestructiveMigration()
.setQueryExecutor(coroutinesTestRule.testDispatcher.asExecutor())
.allowMainThreadQueries()
.build()
// Injecting my memory DB
MyDatabase.setDatabase(database)
}
@After
open fun tearDown() {
if (::database.isInitialized) {
database.clearAllTables()
database.close()
}
// Removing the memory DB
MyDatabase.setDatabase(null)
}
}
@OptIn(ExperimentalCoroutinesApi::class)
class CoroutinesTestRule(
val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()
) : TestWatcher() {
val testScope = TestCoroutineScope(testDispatcher)
val testDispatcherProvider = object : DispatcherProvider {
override fun default(): CoroutineDispatcher = testDispatcher
override fun io(): CoroutineDispatcher = testDispatcher
override fun main(): CoroutineDispatcher = testDispatcher
override fun unconfined(): CoroutineDispatcher = testDispatcher
}
override fun starting(description: Description?) {
super.starting(description)
Dispatchers.setMain(testDispatcher)
}
override fun finished(description: Description?) {
super.finished(description)
Dispatchers.resetMain()
// Reset Coroutine Dispatcher and Scope.
testDispatcher.cleanupTestCoroutines()
testScope.cleanupTestCoroutines()
}
}
class MyTest : BaseTest() {
@Test
@Throws(Exception::class)
fun testRoomDbInsert() = coroutinesTestRule.testDispatcher.runBlocking {
val item = Item(10, true)
database.myDao.insertItem(item)
val list = database.myDao.findItemById(10).take(1).toList()
assertEquals(list[0].id, 10)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment