Espresso是個功能強大、執行速度很快的Android自動化測試框架,但是它有一個重要的局限-你只可以在被測App的Context中操作。
意味著下列App自動化測試需求無法實現:
- 應用的推送消息
- 同步聯系人
- 從另一個應用程序進入被測App
因為你要處理移動設備的其他應用程序,比如通知欄、聯系人等。
事實上,UIAutomator 2.0發布后可以實現上述功能。如Android Developers blog post所說“最重要的是,UIAutomator現在已經基于Android Instrumentation...”,因此,使用Instrumentation test runner既可以運行UIAutomator,也可以運行Espresso。
另外,我們可以將UIAutomator和Espresso測試結合起來,可以更加得心應手的處理被測應用和電話之間的交互。
下面的例子,我將解釋如何使用這種方法來自動化測試App的聯系人同步功能。
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiSelector;
@RunWith(AndroidJUnit4.class)
public class TestContactsSync {
@Rule
public ActivityTestRule mActivityRule = new ActivityTestRule(LoginActivity.class);
UiDevice mDevice;
String PEOPLE_APP = "People";
String MY_APP = "XING";
String userContactName = "Android Tester";
@Before
public void setUp() throws Exception{
super.setUp();
mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
}
@Test
public void testContactsSync() throws Exception {
// Espresso code: login the user, navigate to contact sync and enable clicking on toggle
logInUser();
onView(withText(R.string.sync_button)).perform(click());
onView(withId(R.id.contacts_sync_enable_toggle)).perform(click());
// UIAutomator code: navigate to People app
mDevice.pressHome();
UiObject conutactsApp = mDevice.findObject(new UiSelector().text(PEOPLE_APP));
conutactsApp.clickAndWaitForNewWindow();
// UIAutomator code: check that contact is present in it after sync was triggered
UiObject contactName = mDevice.findObject(new UiSelector().text(userContactName));
assertTrue(contactName.exists());
// UIAutomator code: navigate back to my app under testm
Device.pressHome();
UiObject myApp = mDevice.findObject(new UiSelector().text(MY_APP));
myApp.clickAndWaitForNewWindow();
// Espresso code: turn off contact sync and logout
onView(withId(R.id.contacts_sync_enable_toggle)).perform(click());
onView(withId(R.id.logout)).perform(click());
}
@After
public void tearDown() throws Exception {
super.tearDown();
}
}
是不是很完美?UIAutomator需要Android 4.3(API Level 18)及更高版本。稍微修改下build.gradle
文件即可-添加productFlavors
和聲明uiautomator依賴。
productFlavors {
// The actual application flavor
production {
minSdkVersion 14
}
// Test application flavor for uiautomatior tests
test {
minSdkVersion 18
}
}
dependencies {
// Instrumentation tests
androidTestCompile 'com.android.support.test.espresso:espresso-contrib:2.1'
androidTestCompile 'com.android.support.test:rules:0.2'
// Set this dependency to build and run UI Automator tests
androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.0.0'
}
祝你好運:)