使用 Espresso API 時,我們建議測試創建者從用戶與應用交互時可能會執行哪些操作(即,找到界面元素並與之交互)的角度進行思考。
新建的項目一般都會自動添加如下依賴,如果沒有請添加一下
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
Espresso 測試代碼必須放在 app/src/androidTest 目錄下.這一點我之前就解釋過了。
從一個簡單的案例開始:
在一個Activity中添加一個按鈕,點擊按鈕文本內容變成 Hello Espresso。然後寫單元測試來驗證他
Activity類
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
View button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textView.setText("Hello Espresso");
}
});
}
}
Activity的xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="51dp"
android:text="Button"
app:layout_constraintEnd_toEndOf="@+id/textView"
app:layout_constraintStart_toStartOf="@+id/textView"
app:layout_constraintTop_toBottomOf="@+id/textView" />
</android.support.constraint.ConstraintLayout>
創建測試類
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Rule
public ActivityTestRule<MainActivity> rule = new ActivityTestRule<>(MainActivity.class);
@Test
public void useAppContext() {
// 找到按鈕觸發他的點擊事件
onView(withId(R.id.button)).perform(click());
// 尋找TestView檢測文本內容是否Hello Espresso
onView(withId(R.id.textView)).check(matches(withText("Hello Espresso")));
}
}