我将在Selenium组织一次明确的等待:
WebDriverWait = new WebDriverWait(driver,30);
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(locator));
问题是我的类中没有驱动程序,因为我使用的是PageFactory,而不是测试类中的构造函数:
MyClass myform = PageFactory.InitElements(driver, MyClass.class)
在这种情况下组织明确等待的好决定是什么?
答案 0 :(得分:7)
我建议您按预期使用PageFactory,并为您的类提供一个构造函数,您希望使用显式等待。将脚本和页面对象分开使得将来更容易使用。
public class MyClass {
WebDriverWait wait;
WebDriver driver;
@FindBy(how=How.ID, id="locatorId")
WebElement locator;
// Construct your class here
public MyClass(WebDriver driver){
this.driver = driver;
wait = new WebDriverWait(driver,30);
}
// Call whatever function you want to create
public void MyFunction(){
wait.until(ExpectedConditions.presenceOfElementLocated(locator));
// Perform desired actions that you wanted to do in myClass
}
然后在您的测试用例中使用代码来执行测试。在您的示例中,等待包含在页面内。
public class MyTestClass {
public static void main (string ... args){
WebDriver driver = new FireFoxDriver();
MyClass myForm = PageFactory.initElements(driver,Myclass.class);
myForm.MyFunction();
}
}
此示例是根据Selenium WebDriver实用指南中的示例建模的,可以在此处找到here
答案 1 :(得分:1)
我认为,如果您从其调用者Test类的page类中传递驱动程序,将会是一个更好的解决方案。请参阅下面的实现以更清楚。
页面类别:
public class YourTestPage {
private WebDriver driver;
private WebDriverWait wait;
@FindBy(xpath = "//textarea")
private WebElement authorField;
public YourTestPage(WebDriver driver) {
this.driver = driver;
wait = new WebDriverWait(driver, 15, 50);
PageFactory.initElements(driver,this);
}
public String getAuthorName() {
wait.until(ExpectedConditions.visibilityOf(authorField)).getText();
}
}
测试类别:
public class YourTest{
private YourTestPage yourTestPage;
private WebDriver driver;
@BeforeTest
public void setup() throws IOException {
driver = WebDriverFactory.getDriver("chrome");
yourTestPage = new YourTestPage(driver);
}
@Test
private void validateAuthorName() {
Assert.assertEquals(yourTestPage.getAuthorName(),"Author Name");
}
}