在build.gradle添加对Uiautomator的依赖
dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:25.1.0' testCompile 'junit:junit:4.12' //uiautomator androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.0' }随便写了个demo xml:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="app.test.myapplication.MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView" android:layout_marginStart="14dp" android:text="Button" /> </RelativeLayout>Activity:
private int clicks=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TextView textView= (TextView) findViewById(R.id.textView); findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { textView.setText("click: " + clicks); clicks++; } }); }在androidTest下,添加测试类。
测试代码:
public class MainTest extends UiAutomatorTestCase { public void testMain() throws UiObjectNotFoundException { // getUiDevice().pressHome(); // UiObject Calculator = new UiObject(new UiSelector().description("计算器")); // // Calculator.clickAndWaitForNewWindow(); // UiObject seven = new UiObject(new UiSelector().resourceId("com.android.calculator2:id/digit7")); // seven.click(); // UiObject plus = new UiObject(new UiSelector().resourceId("com.android.calculator2:id/plus")); // plus.click(); // UiObject one = new UiObject(new UiSelector().resourceId("com.android.calculator2:id/digit1")); // one.click(); // UiObject result = new UiObject(new UiSelector().resourceId("com.android.calculator2:id/equal")); // result.click(); // getUiDevice().pressBack(); getUiDevice().pressHome(); Context context = InstrumentationRegistry.getContext(); Intent launchIntent = new Intent(); launchIntent.setComponent(new ComponentName("app.test.myapplication", "app.test.myapplication.MainActivity")); context.startActivity(launchIntent); UiObject main = new UiObject(new UiSelector().resourceId("app.test.myapplication:id/button")); main.click(); } }相关的类:
异常:
官网–Uiautomator
