Trying to write unit Test cases for the DAO class. But after inserting data, when I am trying to fetch data to test then it always returns an empty array.
Check the fetchAllDataCheck() Links that I have followed for writing the test case: https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#0
class NewsDataBaseTest {
@Mock
lateinit var newsDao: NewsDao
@Mock
lateinit var db: AppDatabse
@Mock
lateinit var contextMock: Context
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
newsDao = Mockito.mock(NewsDao::class.java)
contextMock = Mockito.mock(Context::class.java)
db = Room.inMemoryDatabaseBuilder(contextMock, AppDatabse::class.java)
// Allowing main thread queries, just for testing.
.allowMainThreadQueries()
.build()
}
@After
@Throws(IOException::class)
fun closeDB() {
db.close()
}
@Test
@Throws(Exception::class)
fun fetchAllDataCheck() {
val note = listOf(
Article(
null, "Author1", "Title1", "Description1",
"URL1", "URLTOIMAGE1", "12", "content1", null
)
)
newsDao.insert(note)
val note1 = listOf(
Article(
null, "AuthorTest22", "Title22", "Description222",
"UR2L2", "URLTOIMAGE2211", "1212222", "co222ntent", null
)
)
newsDao.insert(note1)
/*till this the test case is passed*/
var allWords = newsDao.getAllNewsData() **// this array is coming empty**
assertEquals(allWords[0].author, "Author1")
assertEquals(allWords[1].author, "AuthorTest22")
}
//DAO Class
@Dao
interface NewsDao {
@Query("SELECT * from tbl_newsData")
fun getAllNewsData(): List<Article>
@Insert(onConflict = REPLACE)
fun insert(newsData: List<Article>)
@Query("DELETE from tbl_newsData")
fun deleteAll()
@Query("DELETE from tbl_newsData")
fun deleteData()
}
The problem is that you are accessing a mocked instance of the NewsDao, should create a real instance of NewsDao or test it on the class that uses the DAO itself. When you mock an object is because you don't want to know about the internal implementation so you can manipulate it. E.g:
@Mock
lateinit var newsDao: NewsDao
init {
Mockito.`when`(newsDao.insert(Any())).then { //do something }
}