Selenium WebDriver - 无法使用 PageObjectModel 访问或单击元素

Selenium WebDriver - Not able to access or click elements using PageObjectModel

我已经使用 Selenium 中的页面对象模型定义了 Web 元素。从测试方法来看,每当我尝试访问这些 Web 元素或对其执行任何操作时,我的测试都会完全跳过它并完成,没有错误。

public class HomePage extends Base{

@FindBy(xpath="//button[@id='sparkButton']")
    public WebElement menuDropDown;

public HomePage(){
        PageFactory.initElements(driver, this);
    }

public void clickHomepagemenuDropDown() {
        menuDropDown.click();
        System.out.println("Print HELLO");
   }
}


public class Test1 extends Base{

  HomePage homepage = new HomePage() ;
  @Test(priority=1)
  public void homePage() throws Exception {
    try {
      //do something
        homepage.clickHomepagemenuDropDown();
      //print something
       }catch (Exception e) {
               System.out.println (e);
                  return;
       }

}

如果我替换homepage.clickHomepagemenuDropDown(); 使用以下几行,我的程序将 运行 正常。

WebElement mdd = driver.findElement(By.xpath("//button[@id='sparkButton']"));
mdd.click();

是否缺少某些设置?

更正捕获消息后更新-- 我得到以下空异常 无法调用“org.openqa.selenium.SearchContext.findElement(org.openqa.selenium.By)”,因为“this.searchContext”为空

在您的 Test1 class 中,您使用字段初始化初始化了 HomePage class,因此 @FindBy(xpath="//button[@id='sparkButton']") 无法找到 Web 元素。当你在测试方法中调用clickHomepagemenuDropDown()时,它会抛出异常并进入catch块。在你刚刚写的 catch 块中 return。由于这个原因,测试跳过并完成,没有错误。我认为你应该在你的测试方法中初始化你的页面对象。

在测试 class 中,尝试创建一个带有 beforetest/beforemethod 注释的方法,并将主页对象放入这些方法中