聲明:本系列文章是對 Android Testing Support Library官方文檔的翻譯,水平有限,歡迎批評指正。
1. Espresso 概覽
2. Espresso 設置說明
3. Espresso 基礎
4. Espresso 備忘錄
5. Espresso 意圖
6. Espresso 高級示例
7. Espresso Web
8. AndroidJUnitRunner
9. ATSL 中的 JUnit4 規則
10. UI Automator
11. 可訪問性檢查
我們在 Android 測試支持庫中提供了一套供 AndroidJUnitRunner
使用的 JUnit 規則。JUnit 規則提供了更多的靈活性,并且減少了測試需要的樣板代碼。
?為了擁抱 ActivityTestRule
和 ServiceTestRule
?,我們不再使用 ??ActivityInstruentationTestCase2
? 和 ServiceTestCase
類型的 TestCase
。
ActivityTestRule
此規則提供了針對單個 activity 的功能測試。待測 activity 將在每個帶 @Test
注解的測試和每個帶 ?@Before
? 注解的方法執行前被啟動。它將在測試結束并且所有帶 ?@After
? 注解的方法執行完后被銷毀。待測 activity 在測試期間可以通過調用 ?ActivityTestRule#getActivity
? 訪問。
@RunWith(AndroidJUnit4.class)
@LargeTest
public class MyClassTest {
@Rule
public ActivityTestRule<MyClass> mActivityRule = new ActivityTestRule(MyClass.class);
@Test
public void myClassMethod_ReturnsTrue() { ... }
}
ServiceTestRule
此規則提供了在測試前后啟動和終止服務的簡單機制。它也會保證當啟動(或綁定)一個服務時,該服務被成功的連接。服務可以使用它的一個幫助方法來啟動(或綁定)。它將在測試結束并且所有帶 ?@After
? 注解的方法執行完后自動被停止(或解綁)。
注意:此規則不適用于 ?IntentService
?,因為它會在 ?IntentService#onHandleIntent(android.content.Intent)
? 結束了所有外發指令時自動銷毀。所以無法保證及時建立一個成功的連接。
@RunWith(AndroidJUnit4.class)
@MediumTest
public class MyServiceTest {
@Rule
public final ServiceTestRule mServiceRule = new ServiceTestRule();
@Test
public void testWithStartedService() {
mServiceRule.startService(
new Intent(InstrumentationRegistry.getTargetContext(), MyService.class));
// test code
}
@Test
public void testWithBoundService() {
IBinder binder = mServiceRule.bindService(
new Intent(InstrumentationRegistry.getTargetContext(), MyService.class));
MyService service = ((MyService.LocalBinder) binder).getService();
assertTrue("True wasn't returned", service.doSomethingToReturnTrue());
}
}