RFT Best Practices - 3. 对象查找

来源:岁月联盟 编辑:zhuzhu 时间:2009-04-27

  如何灵活查找窗体内的对象呢?和查找窗体类似,可以使用这些对象特有的属性,依照一定的查找逻辑进行处理。下面是一个典型的查找方法,以此为例进行说明:

    public TestObject getObject(ArrayList<Property> v) {

        rootTO.waitForExistence(waitMaxTime, waitCheckInterval);
        TestObject returnObject = null;
        TestObject to[] = null;
        double timeNow = System.currentTimeMillis() / 1000;
        double endTime = timeNow waitMaxTime;
        v.add(new Property("showing", "true"));
        while (returnObject == null && timeNow < endTime) {
            to = rootTO.find(atDescendant((Property[]) v.toArray(new Property[0])));
            if (to.length > 1) {
                 throw new AmbiguousRecognitionException("Find more than one object.");
            }
            if (to.length == 1) {
                returnObject = to[0];
            } else
                sleep(waitCheckInterval);
            timeNow = System.currentTimeMillis() / 1000;
        }
        return returnObject;
    }

  上面的方法根据传入的参数集合对当前窗口中的所有对象进行查找。和之前的窗体查找一样,最好显示的添加showing=true参数,因为在Swing程序的运行过程中,内存中会对GUI元素进行缓存,可能一个界面消失了,但它还在内存中,等待着随后被显示。这样一来,就需要这个参数过滤到所有未被显示的GUI元素。在实际使用过程中,可以使用如下的方法进行调用: (调用前使用RFT的对象查看器确定待查找对象的唯一属性)

protected WButton getButton(String name) {
        ArrayList<Property> v = new ArrayList<Property>();
        v.add(new Property(".class", "javax.swing.JButton"));
        v.add(new Property("accessibleContext.accessibleName", name));
        TestObject to = og.getObject(v);
        if (!Utility.exists(to))
            throw new ObjectNotFoundException();
        else
            return new WButton(to);
    } 

  与窗口处理一样,如果某些参数需要使用正则表达式处理,可以使用下面的方法:

    protected WListBox getList(String label) {
        RegularExpression exp = new RegularExpression(".*JComboBox$|.*JList$", false);
        ArrayList<Property> v = new ArrayList<Property>();
        v.add(new Property(".class", exp));
        v.add(new Property(".priorLabel", label));
        TestObject to = og.getObject(v);
        if (!Utility.exists(to))
            throw new ObjectNotFoundException();
        else
            return new WListBox(to);
    } 

  在对象查找过程中,可能需要各种不同的查找逻辑。例如,如果对象可能存在也可能不存在,在查找的时候就不需要等待并反复查找,这时候,可以使用如下的方法:

    public TestObject getObjectWithoutWait(ArrayList<Property> v) {
        rootTO.waitForExistence();
        TestObject returnObject = null;
        v.add(new Property("showing", "true"));
        TestObject to[] = rootTO.find(atDescendant((Property[]) v.toArray(new Property[0])));
        if (to.length > 1) {
            throw new AmbiguousRecognitionException(
                    Find more than one object.);
        }
        if (to.length == 1) {
            returnObject = to[0];
        }
        return returnObject;
    }

  有时候,界面上有多个具有相同属性的对象,只能通过他们的编号来区分他们;有时候需要以某个确定对象为根来进行查找;有时候需要查找直接子对象而不是所有子对象,等等。并且,这些逻辑之间也存在排列组合的情况,实际使用中可以根据自身需要灵活处理。这些方法都是对上面基本方法的扩展,大家可以尝试自己来实现。