将变量传递到使用Selenium Java中的注释定义的webelement

问题描述

我使用批注在selenium java中声明webelement。 在大多数情况下,我有一个简单的定位器:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:background="@color/color_white"
        android:layout_height="match_parent"
        tools:context=".AffectedCountries">
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:layout_margin="10dp"
            android:text="search"
            android:textSize="40dp"
           />
    
        <androidx.recyclerview.widget.RecyclerView
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
            android:layout_below="@id/edtSearch"
            android:layout_margin="5dp"
            android:padding="5dp"
          android:id="@+id/recyclerAffectedCountries">
    
        </androidx.recyclerview.widget.RecyclerView>
    </RelativeLayout>

但是有时候有时候我需要将变量传递到xpath或任何其他定位器中。 在这种情况下,我无需在函数中声明webelement即可这样做,

@FindBy(how = How.ID,using="login")
WebElement btnLogin;

public void clickLogin() {
        btnLogin.click()
    }

我不喜欢它,因为定位器应该在一个地方被调用,而不是与代码可见性混合使用

我想做这样的事情:

 public void clickElement(String elementName) {
         driver.findElementByXpath("//android.widget.TextView[@text='" + elementName + "']")
    }

然后

String elementXpathPrePart= "//android.widget.TextView[@text='";
String elementXpathPostPart = "']";

您对此有任何解决方案吗?

解决方法

好吧,在使用页面工厂时,这是Page对象模型中的常见问题。解决方案:

  1. 使用常量,java文件并保留所有从那里引用的xpath

    公共类常量{ 公共静态最终字符串myxpath =“ // input [@ id ='username'] } 页内类:

    @FindBy(how = How.ID,使用= Constants.myxpath) WebElement btnLogin;

OR

在代码中

override fun onCreateViewHolder(parent: ViewGroup,viewType: Int): MyViewHolder {
    var cell = LayoutInflater.from(parent.context).inflate(R.layout.example_item,parent,false)
 
    return MyViewHolder(cell)
}


class MyViewHolder(
    val itemView: View
) : RecyclerView.ViewHolder(itemView) {
    //TODO get textview here itemView.findViewByID
}