Android自動化測試

一自動化測試簡述

單元測試只能測試一個方法,測試的粒度比較細,對于app來說,用戶頻繁與運行中的APP交互,為了模擬這個場景,在運行中的APP中進行測試,需要一個自動化測試工具進行模擬用戶與APP交互。現在選取的工具是espresso.

二espresso接入

首先在要運行的module的gradle文件添加如下依賴:

testCompile'junit:junit:4.12'

compile'org.apache.commons:commons-lang3:3.0'

androidTestCompile'com.android.support.test:runner:0.5'

androidTestCompile'com.android.support:support-annotations:25.3.1'

androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {

excludegroup:'com.android.support',module:'support-annotations'

})

并在defaultConfig添加一句:

testInstrumentationRunner'android.support.test.runner.AndroidJUnitRunner'

至此,依賴添加完成。

三編寫測試代碼進行測試

開始測試代碼的編寫,把項目切換到Android模式下,下面以靈機作為例子說明,如圖:


可以看到在java文件夾下有三個一樣的文件夾名字,第一個是源代碼目錄,第二個是放自動化測試代碼的目錄,

第三個是放單元測試代碼的目錄。現在在第二各目錄放自動化測試代碼。

新建LoginTest類:


這是測試登錄功能,測試有個奇特的地方,測試代碼要配置要測試的activity,啟動測試時將直接打開該activity,但在測試過程中可以跳轉到其他activity,并繼續測試。配置activity語句為:

@Rule

publicActivityTestRulemActivityRule=newActivityTestRule<>(LoginActivity.class);

用到了注解,以為測試登錄,將用代碼生成用戶名,密碼,代碼如下:

publicStringGetRandomUserName() {

String path = RandomStringUtils.random(random.nextInt(8),'4','的','到','G','B','C','分','個',

'從');

returnpath;

}

publicStringGetRandomPassword() {

String path = RandomStringUtils.random(random.nextInt(8),'E','G','B','C','K',

'G');

returnpath;

}

測試的思路是利用代碼模擬用戶輸入及點擊登錄按鈕,在espresso,利用onView(withId(R.id.XXX))尋找activity的控件,再利用perform()方法進行相應的動作,例如輸入文字或點擊按鈕,

在靈機的登錄界面,輸入用戶名及密碼的語句為:

onView(withId(R.id.eit_login_userName)).perform(replaceText(GetRandomUserName()));

onView(withId(R.id.eit_login_userPassword)).perform(replaceText(GetRandomPassword()));

replaceText方法是輸入文字的意思。、

輸入后就點擊登錄按鈕:

onView(withId(R.id.btn_login_sumbit)).perform(click());

因為想不停輸入用戶名密碼,點擊登錄,在外層加了個循環,整個LoginTest類如下:

@RunWith(AndroidJUnit4.class)

@LargeTest

public classLoginTest {

privateRandomrandom=newRandom();

@Rule

publicActivityTestRulemActivityRule=newActivityTestRule<>(

LoginActivity.class);

publicStringGetRandomUserName() {

String path = RandomStringUtils.random(random.nextInt(8),'4','的','到','G','B','C','分','個',

'從');

returnpath;

}

publicStringGetRandomPassword() {

String path = RandomStringUtils.random(random.nextInt(8),'E','G','B','C','K',

'G');

returnpath;

}

@Test

public voidloginWithWrongPassword() {

while(true) {

onView(withId(R.id.eit_login_userName)).perform(replaceText(GetRandomUserName()));

onView(withId(R.id.eit_login_userPassword)).perform(replaceText(GetRandomPassword()));

onView(withId(R.id.btn_login_sumbit)).perform(click());

}

}

}

測試邏輯在loginWithWrongPassword()方法,很簡單。

點擊右鍵直接run這個方法,效果見視頻。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容