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


Android自動化測試-UiAutomator環境搭建(QQ交流群:490451176)

一、環境准備

  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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM