I am learning Kotlin to build a note app. I have created a repository class as shown below which takes a Dao parameter. For now, the source of data is just Dao but in the tutorial I am following, it calls an API class as well.
What I want to know is how do I test a repository classes logic?
import androidx.lifecycle.LiveData
import com.example.lastnotetakingapp.db.daos.NoteDao
import com.example.lastnotetakingapp.db.models.Note
class NotesRepo(private val notesDao: NoteDao) {
val allNotes: LiveData<List<Note>> = notesDao.getAllNotes()
suspend fun addNewNote(note: Note): Long {
return notesDao.addNewNote(note)
}
}
My test which is passing but it is 100% identical to the way a Dao would be tested except I use repo object, which made wonder if I am doing it right or not:
Is mocking the Database/DAO possible so I can spy on them to make sure they are called and all?
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.example.lastnotetakingapp.db.NoteDB
import com.example.lastnotetakingapp.db.daos.NoteDao
import com.example.lastnotetakingapp.db.models.Note
import com.example.lastnotetakingapp.testHelpers.getOrAwaitValue
import com.google.common.truth.Truth
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class NotesRepoTest {
private lateinit var dao: NoteDao
private lateinit var db: NoteDB
private lateinit var notesRepo: NotesRepo
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
@Before
fun setUp(){
db = Room.inMemoryDatabaseBuilder(
ApplicationProvider.getApplicationContext(),
NoteDB::class.java,
).allowMainThreadQueries().build()
dao= db.noteDao
notesRepo = NotesRepo(dao)
}
@After
fun tearDown(){
db.close()
}
@Test
fun saveNotesTest(): Unit = runBlocking{
val note = Note(0, "tupac", "content", 0)
val id : Long = notesRepo.addNewNote(note)
Truth.assertThat(id).isEqualTo(1)
val notes = notesRepo.allNotes.getOrAwaitValue()
val noteOne: Note? = notes?.get(0)
Truth.assertThat(notes?.size).isEqualTo(1)
Truth.assertThat(noteOne?.title).isEqualTo(note.title)
Truth.assertThat(noteOne?.content).isEqualTo(note.content)
Truth.assertThat(noteOne?.viewed).isEqualTo(false)
}
}