到目前幾乎所有的功能都做好了,但是我想要說說一個比較重要的功能:Test
或許現在專案比較小還感受不出來,但是對於大的項目來說,合理的分工是很必要的,在每個部門各司其職的時候如果出錯就要一個部分一個部分找問題,十分低效,因此,在每個部份的程式都先Test過就可以大量減少出錯的概率
Test分成了邏輯與UI的測試,分別可以測試資料流動取得與UI位置Navigator
Test的訊息中通常包含覆蓋率,代表說這些Test大概跑過多少的程式,但請注意覆蓋率100%不代表不會有問題,比如說一些型別轉換或null value的問題就無法發現
也因此,我是不認為這個那麼小的專案是需要test的,但是為了比較全面的展示功能,所以會寫test
在專案結構中叫做androidTest,通常稱為Instrumented test,也就是需要有幾乎一樣的環境才能夠跑的,比如說需要context的database與datastore
在專案結構中叫做Test,他只負責測試邏輯,如果說你使用的ViewModel沒有database,就可以放在這邊
他需要一些依賴,像是
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
androidTestImplementation(platform(libs.androidx.compose.bom))
androidTestImplementation(libs.androidx.compose.ui.test.junit4)
但這些都是內建的不用額外添加
這邊大概講Test的架構
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
這是Unit test
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.tutorial2025", appContext.packageName)
}
}
這是Instrumented test
有幾個常用的annotation
@Test
測試的內容@Before
先將需要的數據給初始化,像是context取得@After
將數據刪除等