Android Local Unit Test
針對Android 單元測試中, 對於不需要測試實機環境的函數時, 我們可用 Local Unit Test 的方式來測試.
(請參閱 Android App Test 基本概念)
在談到如何建立測試之前, 首先先了解 JUnit 的測試順序.
JUnit4 測試順序由Annotation決定
@BeforeClass : 在開始第一個測試前執行
@Before : 每次測試前執行
@Test : 表示要執行此區段裡的測試碼
@Test(timeout=5000) : 可設定多少時間內要完成的測試項目
@After : 每次測試後執行
@AfterClass : 全部測試完畢後執行
如以下內容
1 | public class MathUtilsTest { |
則順序為
testBeforeClass() -> testBefore() -> testTest1() -> testAfter() -> testBefore() -> testTest2() -> testAfter() -> testAfterClass()
Step 1: 建立函數 (被測試函數)
1 | public class MathUtils { |
此範例為找到下一個2次方的數.
如輸入10, 則回傳為 16
因為 2^3 = 8, 2^4 = 16, 而 8 < 10 < 16
所以下一個2次方的數為16
Step 2: 建立測試檔
利用 Ctrl + Shift + T 建立 MathUtilsTest.java
位置儲存於 /src/test/java/ package_path /
Step 3: 確認測試檔是否位於 JUnit 中
Run -> Edit Configuations
若發現測試檔案不屬於JUnit, 先刪除相關測試後, 再重新執行Step 2.
Step 4: Run Test
Project列表中, 在測試檔點擊右鍵, 執行
Android Local Unit Test
https://nickcarter9.github.io/2016/07/27/2016/2016_07_27-android-unit_test/