系列教程
- 在Android Studio中進(jìn)行單元測試和UI測試 - 1.概述
- 在Android Studio中進(jìn)行單元測試和UI測試 - 2.創(chuàng)建新的Android Studio工程
- 在Android Studio中進(jìn)行單元測試和UI測試 - 3.配置支持單元測試的工程
- 在Android Studio中進(jìn)行單元測試和UI測試 - 4.創(chuàng)建第一個(gè)單元測試
- 在Android Studio中進(jìn)行單元測試和UI測試 - 5.運(yùn)行單元測試
- 在Android Studio中進(jìn)行單元測試和UI測試 - 6.配置支持Instrumentation測試的工程
在使用Espresso進(jìn)行UI測試前,讓我們?yōu)閍pp添加一些Views和簡單的交互。我們使用一個(gè)用戶可以輸入名字的EditText,歡迎用戶的Button和用于輸出的TextView。打開res/layout/activity_main.xml
,粘貼如下代碼:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:text="@string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:hint="Enter your name here"
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textView"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Say hello!"
android:layout_below="@+id/editText"
android:onClick="sayHello"/>
</RelativeLayout>
還需要在MainActivity.java
中添加onClick handler:
MainActivity.java
public void sayHello(View v){
TextView textView = (TextView) findViewById(R.id.textView);
EditText editText = (EditText) findViewById(R.id.editText);
textView.setText("Hello, " + editText.getText().toString() + "!");
}
現(xiàn)在可以運(yùn)行app并確認(rèn)一切工作正常。在點(diǎn)擊Run按鈕之前,確認(rèn)你的Run Configuration沒有設(shè)置為運(yùn)行測試。如需更改,點(diǎn)擊下拉選項(xiàng),選擇app。
下一篇:在Android Studio中進(jìn)行單元測試和UI測試 - 8.創(chuàng)建并運(yùn)行Espresso測試