iT邦幫忙

2025 iThome 鐵人賽

DAY 26
0
Mobile Development

現代Android jetpack compose開發入門系列 第 26

Day 26:使用Test確認程式的邏輯

  • 分享至 

  • xImage
  •  

到目前幾乎所有的功能都做好了,但是我想要說說一個比較重要的功能:Test

為什麼要寫Test

或許現在專案比較小還感受不出來,但是對於大的項目來說,合理的分工是很必要的,在每個部門各司其職的時候如果出錯就要一個部分一個部分找問題,十分低效,因此,在每個部份的程式都先Test過就可以大量減少出錯的概率
Test分成了邏輯與UI的測試,分別可以測試資料流動取得與UI位置Navigator
Test的訊息中通常包含覆蓋率,代表說這些Test大概跑過多少的程式,但請注意覆蓋率100%不代表不會有問題,比如說一些型別轉換或null value的問題就無法發現
也因此,我是不認為這個那麼小的專案是需要test的,但是為了比較全面的展示功能,所以會寫test

UI Test

在專案結構中叫做androidTest,通常稱為Instrumented test,也就是需要有幾乎一樣的環境才能夠跑的,比如說需要context的database與datastore

Unit Test

在專案結構中叫做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將數據刪除等
    我認為有一些東西就很不適合用Test,像是datastore
    其實不會寫test也沒關係,只要能看得懂就好了

上一篇
Day 25:將DataStore套用在應用上
下一篇
Day 27:為應用添加測試
系列文
現代Android jetpack compose開發入門27
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言