Android UIAutomator 自动化测试
2016-11-17 本文已影响341人
一路摇到顶
uiautomator 自动化测试框架,使用java编写测试脚本,进行黑盒测试,进行ui测试。可以对任何app进行测试,他模拟的是人的操作。需要sdk 18 以上。
- 环境配置
在com.example.android.testing.uiautomator.BasicSample,下新建测试类。如图所示。
ChangeTextBehaviorTest
这是Google给的案例。了解了解基本都会用了。AutoSendWeChatMessageTest
,调起微信发送信息。其实挺简单的。哈哈。
-
分析界面,获取界面信息
使用[sdk]/tools/uiautomatorviewer 下,查看你需要测试的界面。点击截图。查看整个界面的ui元素。 -
编写代码
/** * Created by azezer0 on 16/11/17. */ @RunWith(AndroidJUnit4.class) //测试用例 @SdkSuppress(minSdkVersion = 18)//最小版本 public class AutoSendWeChatMessageTest { public static final String Tag = AutoSendWeChatMessageTest.class.getSimpleName(); private static final String BASIC_SAMPLE_PACKAGE = "com.tencent.mm"; private static final int LAUNCH_TIMEOUT = 5000; private static final String STRING_TO_BE_TYPED = "UiAutomator"; private UiDevice mDevice; @Before //测试用例前置操作 public void startWeChat() { mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); //获取界面实例 mDevice.pressHome(); // Wait for launcher final String launcherPackage = getLauncherPackageName(); //获取桌面启动器的包名 assertThat(launcherPackage, notNullValue()); mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT); //等待时间 // Launch the blueprint app Context context = InstrumentationRegistry.getContext(); final Intent intent = context.getPackageManager() .getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); // Clear out any previous instances context.startActivity(intent); // Wait for the app to appear mDevice.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)), LAUNCH_TIMEOUT); } @Test public void sendMessage() throws UiObjectNotFoundException { // Type text and then press the button. UiObject2 title = mDevice.findObject(By.text("我们都是程序猿")); //根据文本查找控件 Assert.assertNotNull(title); title.click(); //点击事件 UiObject2 a2a = mDevice.findObject(By.res(BASIC_SAMPLE_PACKAGE, "a2a")); //根据id查找控件 a2a.setText("我是通过uiautomator发送的"); //设置文本 mDevice.waitForIdle(); //等待界面禁止 UiObject2 a2g = mDevice.findObject(By.res(BASIC_SAMPLE_PACKAGE, "a2g"));// a2g.click(); } /** * Uses package manager to find the package name of the device launcher. Usually this package * is "com.android.launcher" but can be different at times. This is a generic solution which * works on all platforms.` */ private String getLauncherPackageName() { // Create launcher Intent final Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); // Use PackageManager to get the launcher package name PackageManager pm = InstrumentationRegistry.getContext().getPackageManager(); ResolveInfo resolveInfo = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY); return resolveInfo.activityInfo.packageName; } }
-
UIWatch
mDevice.registerWatcher("phone", new UiWatcher() {
@Override
public boolean checkForCondition() {
// just press back
//进行获取界面元素,确定当前是不是前面我们进行测试的界面。
//如果不是 当前界面 返回true。是的话返回false
}
});