Skip to content

Commit

Permalink
Add base dao test for reduce boilerplate for testing DAOs
Browse files Browse the repository at this point in the history
  • Loading branch information
AkshayChordiya committed Jul 10, 2020
1 parent 6cb2e19 commit bd3c330
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 18 deletions.
27 changes: 27 additions & 0 deletions app/src/androidTest/java/com/akshay/newsapp/core/utils/DaoTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.akshay.newsapp.core.utils

import android.content.Context
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.test.core.app.ApplicationProvider
import org.junit.After
import org.junit.Before

/**
* Base class to reduce boilerplate code for testing DAO(s) of [RoomDatabase].
*/
abstract class DaoTest<Database: RoomDatabase>(
private val database: Class<Database>
): MockitoTest() {

protected lateinit var db: Database

@Before
override fun setup() {
super.setup()
db = Room.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext<Context>(), database).build()
}

@After
fun teardown() = db.close()
}
Original file line number Diff line number Diff line change
@@ -1,31 +1,17 @@
package com.akshay.newsapp.news.storage

import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.akshay.newsapp.core.utils.DaoTest
import com.akshay.newsapp.core.utils.assertItems
import com.akshay.newsapp.news.model.NewsArticles
import kotlinx.coroutines.runBlocking
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
class NewsArticlesDaoTest {

private lateinit var db: NewsDatabase

@Before
fun initDb() {
db = Room.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext<Context>(), NewsDatabase::class.java).build()
}

@After
fun closeDb() = db.close()
class NewsArticlesDaoTest : DaoTest<NewsDatabase>(NewsDatabase::class.java) {

@Test
@Throws(InterruptedException::class)
Expand All @@ -50,5 +36,4 @@ class NewsArticlesDaoTest {
// THEN
db.newsArticlesDao().getNewsArticles().assertItems(input)
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import org.mockito.MockitoAnnotations
abstract class MockitoTest {

@Before
fun setup() {
open fun setup() {
MockitoAnnotations.initMocks(this)
}
}

0 comments on commit bd3c330

Please sign in to comment.