UIAutomator2.0详解(UIDevice篇----获取控件)

UIDevice提供了3个获取控件的方法,和一个判断控件是否存在的方法。

public UiObject findObject(UiSelector selector)
public UiObject2 findObject(BySelector selector)
public List findObjects(BySelector selector)
public boolean hasObject(BySelector selector)

在UIAutomator2.0中,控件类型有两种,UIObject和UIObject2。而对应的传参也有两种,分别为UISelect和BySelector。对于四者的关系,前文(http://blog.csdn.net/daihuimaozideren/article/details/78625099)已经说过,这里不再重复。本文仅简单记录一下四种方法的使用。

还是用简单的示例来演示。核心代码如下:

public class UIObjectTest extends UIDeviceTest {

    private String text_Text="input";

    private String mPackageName="com.breakloop.test";

    private String mActivityName=".MainActivity";

    private long timeout=2000l;

    @Before
    public void start(){
        Utils.startAPP(mDevice,mPackageName,mActivityName);
        waitForAMoment();
    }

    private void waitForAMoment(){
        mDevice.waitForWindowUpdate(mPackageName,timeout);
    }

    @After
    public void end(){
        Utils.closeAPP(mDevice,mPackageName);
        waitForAMoment();
    }

    @Test
    public void test1(){
        UiObject2 uiObject2=null;
        UiObject uiObject=null;
        List uiObject2List=null;
        boolean result=false;
        String input1="hello";
        String input2="world";

        Log.i(TAG, "start");
        result=mDevice.hasObject(By.textStartsWith(text_Text));
        Log.i(TAG, (result?"":"Do Not ")+"find UI start with "+text_Text);
        waitForAMoment();

        uiObject2=mDevice.findObject(By.textStartsWith(text_Text));
        if(uiObject2!=null){
            uiObject2.setText(input1);
            waitForAMoment();
            uiObject2.setText(text_Text);
        }
        waitForAMoment();

        uiObject2List=mDevice.findObjects(By.textStartsWith(text_Text));
        if(uiObject2List!=null){
            Log.i(TAG, "find "+uiObject2List.size()+" items");
            for (UiObject2 item :
                    uiObject2List) {
                item.setText(input2);
                waitForAMoment();
            }
        }

        uiObject=mDevice.findObject(new UiSelector().textStartsWith(input2));
        if(uiObject!=null){
            Log.i(TAG, "find UIObject by text "+input2);
            uiObject2.setText(input1);
        }
        waitForAMoment();
        Log.i(TAG, "end");        
    }
}

执行效果如图:

执行结果如下:

11-27 23:33:40.544 I/com.breakloop.u2demo.uidevice.UIObjectTest: start
11-27 23:33:40.613 I/com.breakloop.u2demo.uidevice.UIObjectTest: find UI start with input
11-27 23:33:47.611 I/com.breakloop.u2demo.uidevice.UIObjectTest: find 2 items
11-27 23:33:51.699 I/com.breakloop.u2demo.uidevice.UIObjectTest: find UIObject by text world
11-27 23:33:53.761 I/com.breakloop.u2demo.uidevice.UIObjectTest: end

需要指出的是:

UIAutomator2.0详解(UIDevice篇----获取控件)_第1张图片

(1)如果有多个符合条件的控件存在,findObject只返回从根目录开始遍历所找到的第一个控件对象。

(2)以txt为遍历依据的查询条件,对hint同样生效。

当然,获取控件的方法,取决于遍历条件。如何用好By和UISelector则是关键了。

你可能感兴趣的:(android测试,Android自动化测试)