Skip to content

Instantly share code, notes, and snippets.

@ProArun
Created August 19, 2023 16:32
Show Gist options
  • Save ProArun/6d88ce0163a7388b39e30b6951c4c1bf to your computer and use it in GitHub Desktop.
Save ProArun/6d88ce0163a7388b39e30b6951c4c1bf to your computer and use it in GitHub Desktop.
Room database testing
plugins{
id 'kotlin-kapt'
}
dependencies {
def room_version = "2.4.3"
implementation "androidx.room:room-runtime: $room_version"
implementation "androidx.room:room-ktx: $room_version"
kapt "androidx.room:room-compiler: $room_version"
testImplementation "androidx.room:room-testing: $room_version"
androidTestImplementation "androidx.room:room-testing: $room_version"
testImplementation "androidx.arch.core:core-testing:2.1.0"
androidTestImplementation "androidx.arch.core:core-testing:2.1.0"
}
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
fun <T> LiveData<T>.getOrAwaitValue(
time: Long = 2,
timeUnit: TimeUnit = TimeUnit.SECONDS,
afterObserve: () -> Unit = {}
): T {
var data: T? = null
val latch = CountDownLatch(1)
val observer = object : Observer<T> {
override fun onChanged(value: T) {
data = value
latch.countDown()
[email protected](this)
}
}
this.observeForever(observer)
afterObserve.invoke()
// Don't wait indefinitely if the LiveData is not set.
if (!latch.await(time, timeUnit)) {
this.removeObserver(observer)
throw TimeoutException("LiveData value was never set.")
}
@Suppress("UNCHECKED_CAST")
return data as T
}
@Entity
data class Quote(
@PrimaryKey(autoGenerate = true)
val id: Int,
val text: String,
val author: String
)
@Database(entities = [Quote::class],version = 1)
abstract class QuoteDatabase : RoomDatabase(){
abstract fun quoteDao(): QuotesDao
}
interface QuotesDao {
@Insert
suspend fun insertQuote(quote: Quote)
@Update
suspend fun updateQuote(quote: Quote)
@Query("DELETE FROM quote")
suspend fun delete()
@Query("SELECT * FROM quote")
fun getQuotes():LiveData<List<Quote>>
@Query("SELECT * FROM quote where id = :quoteId")
suspend fun gerQuoteById()
}
class QuotesDaoTest{
@get:Rule
val instantExecutorRule = InstantTaskExecutorRule()//this will execute architecture component code syncronasly
lateinit var quoteDatabase: QuoteDatabase
lateinit var quotesDao: QuotesDao
@Before
fun setUp(){
quoteDatabse = Room.inMemoryDatabseBuilder(
ApplicationProvider.getApplicationContext(),
QuoteDatabase::Class.java
).allowMainThreadQueries().build()//allowMainThreadQueries():- This method will makesure all query will run on main thread.
quotesDao = quoteDatabase.quoteDao()
}
@After
fun tearDown(){
quoteDatabase.close()
}
@Test
fun `insertQuote expected single quote`() = runBlocking{//this runBlocking will block the thread until all the code of this methord is not executed
val quote = Quote(id:0,text:"This is a test quote",author:"CheezyCode")
quotesDao.insertQuote(quote)
val result = quotesDao.getQuotes().getOrAwaitValue()
Assert.assertEquals(1,result.size)
Assert.assertEquals("This is a test quote",reqult[0].text)
}
@Test
fun `deleteQuote expected no quote`() = runBlocking{//this runBlocking will block the thread until all the code of this methord is not executed
val quote = Quote(id:0,text:"This is a test quote",author:"CheezyCode")
quotesDao.insertQuote(quote)
quotesDao.delete()
val result = quotesDao.getQuotes().getOrAwaitValue()
Assert.assertEquals(0,result.size)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment