以前 Coroutine 我都念協程,後來才知道這是中國用語,國家教育研究院翻譯是共常式,所以以下都念共常式
private var note = MutableLiveData<Note?>()
init {
initDatabase()
}
private fun initDatabase() {
viewModelScope.launch {
note.value = getNoteFromDatabase()
}
}
private suspend fun getNoteFromDatabase(): Note? {
return database.note()
}
假如要插入資料
viewModelScope.launch {
val note = Note()
//insert(newNight)
database.insert(note)
note.value = getNoteFromDatabase()
}
https://developer.android.com/training/data-storage/room/testing-db
先看Dao 有沒有 Impl 的檔案,沒有的話 ReBuild 讓他建立,如果還是沒有,檢查類別上面有沒有缺少的@標記
Dao 檔案先不要加上 suspend,不然會測試失敗
import org.junit.Assert.assertEquals
@RunWith(AndroidJUnit4::class)
class NoteDatabaseTest {
private lateinit var dao: NoteDatabaseDao
private lateinit var db: NoteDatabase
@Before
fun createDb() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
db = Room.inMemoryDatabaseBuilder(context, NoteDatabase::class.java)
.allowMainThreadQueries()
.build()
dao = db.NoteDatabaseDao
}
@After
@Throws(IOException::class)
fun closeDb() {
db.close()
}
@Test
@Throws(Exception::class)
fun insertAndGetFirst() {
val note = Note()
dao.insert(note)
val note = dao.getFirst()
assertEquals(要測試的內容)
}
}