1. 程式人生 > >Android自動化測試-UiAutomator環境搭建

Android自動化測試-UiAutomator環境搭建

ini runner 代碼 imp event before image lap interrupt

Android自動化測試-UiAutomator環境搭建

一、環境準備

  1. 安裝android sdk,並配置環境變量

  2. 安裝android studio,國內訪問官網受限,如果下載不到,可以到我的百度雲盤下載:

    https://pan.baidu.com/s/1bpq5wK3

   此雲盤中有uiautomator2所依賴的jar包,可以同時下載

   技術分享

二、新建Android Studio工程

  技術分享

  新建一個project,輸入application name,下一步,

  技術分享

  默認選擇,下一步,

  技術分享

  選擇 empty activity:

  技術分享

  最後finish之後,切換到project視圖;

  技術分享

  右擊工程,新建一個libs,並把網盤中下載的uiautomator依賴的jar包,copy進來,並添加依賴,

  技術分享

  Add As Library之後,會彈出一個小框,選擇app,點擊OK

  技術分享

  這樣我們的工程就建好了,左上角,把我們的project模式切換成android模式,

  技術分享

  現在android視圖模式下,界面就比較簡潔直觀了,如下圖所示:標註android test的地方,就是我們要寫測試用例的包,

  技術分享

  新家一個java class,輸入class name,現在我們就可以開開心心的寫測試代碼了

三、測試實例

  下面我們寫一個例子,啟動模擬器,模擬器home上有個chrome瀏覽器,操作步驟:點擊chrome-輸入www.baidu.com-enter;

  點擊android studio上的 AVD manager,就可以啟動模擬器,模擬器界面如下:

  技術分享

  技術分享

  測試用例:

    1. 點擊chrome

    2. 輸入www.baidu.com

    3. Enter

  代碼如下:

    技術分享

  技術分享

  寫好測試用例之後,我們就可以運行了,在運行之前,我們先看下運行配置:

  技術分享

  在配置文件中,一定要有如下一行代碼,如果沒有,可以自己加上:

  testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

  現在就可以運行了,打開你的模擬器,看下界面有什麽效果:

  技術分享

  完整代碼如下:

技術分享
 1 import android.app.Instrumentation;
 2 import android.support.test.InstrumentationRegistry;
 3 import android.support.test.runner.AndroidJUnit4;
 4 import android.support.test.uiautomator.UiDevice;
 5 import android.support.test.uiautomator.UiObject;
 6 import android.support.test.uiautomator.UiObjectNotFoundException;
 7 import android.support.test.uiautomator.UiSelector;
 8 import android.view.KeyEvent;
 9 
10 import org.junit.Before;
11 import org.junit.Test;
12 import org.junit.runner.RunWith;
13 
14 /**
15  * Created by tianxing on 2017/8/15.
16  */
17 
18 @RunWith(AndroidJUnit4.class)
19 public class helloworld {
20 
21     UiDevice uiDevice;
22     Instrumentation instrumentation;
23 
24     @Before
25     public void setUp(){
26         instrumentation = InstrumentationRegistry.getInstrumentation();
27         uiDevice = UiDevice.getInstance(instrumentation);
28     }
29 
30     @Test
31     public void launchChrome(){
32           UiObject chrome = uiDevice.findObject(new UiSelector().text("Chrome"));
33           UiObject searchContent = uiDevice.findObject(new UiSelector().text("Search or type URL"));
34 
35         try {
36             chrome.click();
37             sleep(2000);
38             searchContent.setText("www.baidu.com");
39             uiDevice.pressKeyCode(KeyEvent.KEYCODE_ENTER);
40         } catch (UiObjectNotFoundException e) {
41             e.printStackTrace();
42         }
43 
44     }
45 
46     public void sleep(int mint){
47         try{
48             Thread.sleep(mint);
49         }catch (InterruptedException e){
50             e.printStackTrace();
51         }
52     }
53 
54 }
View Code

Android自動化測試-UiAutomator環境搭建