Robotium 框架学习之Class By

Class By定义了页面元素的定位和支持哪些页面元素(至少我是这么理解的),使用及其简单:Used in conjunction with the web methods. Examples are By.id(String id) and By.cssSelector(String selector),下面只举一个CssSelector的具体源码来分析下是如何实现的:

public abstract class By {

......

 /**
  * Select a WebElement by its css selector.
  * @param selectors the css selector of the web element
  * @return the CssSelector object
  */

 public static By cssSelector(final String selectors) {
  return new CssSelector(selectors);

 }

......

 static class CssSelector extends By {
  private final String selector;

  public CssSelector(String selector) {
   this.selector = selector;
  }

  @Override
  public String getValue(){
   return selector;
  }
 }

这里先定义了一个抽象类By, cssSelector的数据类型是By, 传了一个常量selectors, 并且需要返回一个selector常量, 在下面是内部new的方法的具体实现,分析下在Java技术上用到的一些东西:

1)首先,定义了一个抽象类By,为什么是定义一个抽象类而不是一个接口? 因为在抽象类中可以写具体的实现,如果写成接口则以后每个类都需要具体实现

Which should you use, abstract classes or interfaces?

  • Consider using abstract classes if any of these statements apply to your situation:
    • You want to share code among several closely related classes.
    • You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
    • You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
  • Consider using interfaces if any of these statements apply to your situation:
    • You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
    • You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
    • You want to take advantage of multiple inheritance of type.

2)方法返回数据类型为定义的抽象类本身By:做了一定的规定,返回的一定是By定义的相关数据类型,

3)静态内部类继承了By这个抽象类:静态内部类,不需要实例化即可使用

4)实现了具体的方法:  public CssSelector(String selector) {
                                                 this.selector = selector;

5)重写了getValue方法:原先是默认为空,现在是返回该selector的内存引用。

posted @ 2014-09-15 15:00  思考的犀牛  阅读(190)  评论(0编辑  收藏  举报