ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

如何在Android设备的uiautomator测试用例中打开wifi?

2019-08-26 01:24:15  阅读:158  来源: 互联网

标签:uiautomator android


我想在android中使用uiautomator工具打开wifi作为测试用例的一部分.我尝试在uiautomator测试用例中使用以下代码:

WifiManager wi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
      if(wi.isWifiEnabled()){
        wi.setWifiEnabled(false);
      }else{
        wi.setWifiEnabled(true);
    }

但它给出了这个错误:

“getSystemservice” method is undefined for Mainclass

解决方法:

您实际上可以使用UIAutomator来打开和关闭WiFi设置.我今天晚上写了代码:)

这是代码.您可以将其添加到Android示例(此处为http://developer.android.com/tools/testing/testing_ui.html)

在类的顶部添加以下枚举

private enum OnOff {
    Off,
    On
};

之后添加新代码:

    // Validate that the package name is the expected one
    UiObject settingsValidation = new UiObject(new UiSelector()
    .packageName("com.android.settings"));
    assertTrue("Unable to detect Settings", settingsValidation.exists());

这是新代码:

    UiSelector settingsItems = new UiSelector().className(android.widget.TextView.class.getName());
    UiObject wiFi = appViews.getChildByText(settingsItems, "Wi-Fi");

    // We can click on Wi-Fi, e.g. wiFi.clickAndWaitForNewWindow();
    // So we know we have found the Wi-Fi setting

    UiSelector switchElement = new UiSelector().className(android.widget.Switch.class.getName());
    setSwitchTo(OnOff.Off); // Or set it to On as you wish :)
}   

private void setSwitchTo(OnOff value) throws UiObjectNotFoundException {

    String text;
    UiObject switchObject = getSwitchObject();
    for (int attempts = 0; attempts < 5; attempts++) {
        text = switchObject.getText();
        boolean switchIsOn = switchObject.isChecked();
        final OnOff result;
        if (switchIsOn) {
            result = OnOff.On;
        } else {
            result = OnOff.Off;
        }

        System.out.println("Value of switch is " + switchObject.isSelected() + ", " + text + ", " + switchIsOn);
        if (result == value) {
            System.out.println("Switch set to correct value " + result);
            break;
        } else {
            switchObject.click();
        }
    }
}

private UiObject getSwitchObject() {
    UiObject switchObject = new UiObject(new UiSelector().className(android.widget.Switch.class.getName()));
    assertTrue("Unable to find the switch object", switchObject.exists());
    String text;
    return switchObject;
}

循环是为了补偿我观察到的一些行为,其中点击似乎没有改变开关位置.

标签:uiautomator,android
来源: https://codeday.me/bug/20190826/1724753.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有