-
之前提到在androidTest中进行的是UI测试,这次使用的是Uiautomator,使用Java进行Ui测试
-
打开uiautomator viewer(sdk\tools\bin下)
- 在androidTest中创建class->UiTest
- 方法名一定要以Test开头
package com.example.adminstator.myapplication;
import android.app.Instrumentation;
import android.content.Context;
import android.os.RemoteException;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;
import junit.framework.TestCase;
/**
* Created with Android Studio.
* Description:
* User: wjx
* Date: 2019-05-09
* Time: 12:30
*/
public class UiTest extends TestCase {
public void testA() throws UiObjectNotFoundException, RemoteException {
//获取设备
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
UiDevice uiDevice = UiDevice.getInstance(instrumentation);
//获取上下文
Context context = instrumentation.getContext();
// uiDevice.click(102, 227);
//先回到主界面
uiDevice.pressHome();
//获取浏览器对象,并单击
UiObject browserObject = new UiObject(new UiSelector().text("浏览器"));
browserObject.clickAndWaitForNewWindow();
//获取搜索框对象,并单击
UiObject editObject = new UiObject(new UiSelector().className("android.widget.EditText"));
editObject.click();
uiDevice.pressDelete();
editObject.setText("www.baidu.com");
uiDevice.pressEnter();
//等待网页
uiDevice.sleep();
}
}
-
UiDevice类介绍
- UiDevice代表设备状态
- UiDevice功能:
- 获取设备信息:屏幕分辨率,旋转状态,亮灭屏状态等
- 操作:按键,坐标 操作,滑动,拖拽,灭屏唤醒屏幕,截图等。
- 监听器的功能
-
按键与KeyCode使用
- 手机常见按键:
- Home
- Menu
- Back
- Volume_up
- Volume_Down
- ReventApps
- Power
- Dpad //轨迹球太老旧
- 手机常见按键:
public void testB() throws UiObjectNotFoundException{
//获取UiDevice的方式
UiDevice uiDevice =
UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
// getUiDevice().pressHome();此方法容易出现空指针异常
UiDevice.getInstance().pressMenu();
}
- KEYCODE 键盘映射码:
- KeyEvent按键事件
- META Key
- 辅助功能键:ALT, SHIT, CAPS_LOCK
public void testC() throws UiObjectNotFoundException{
//获取UiDevice的方式
UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
//输入小写abc
uiDevice.pressKeyCode(KeyEvent.KEYCODE_A);
uiDevice.pressKeyCode(KeyEvent.KEYCODE_B);
uiDevice.pressKeyCode(KeyEvent.KEYCODE_C);
//输入大写ABC
uiDevice.pressKeyCode(KeyEvent.KEYCODE_A,1);
uiDevice.pressKeyCode(KeyEvent.KEYCODE_B,1);
uiDevice.pressKeyCode(KeyEvent.KEYCODE_C,1);
}
}