【问题标题】:Selenium WebDriver - Not able to access or click elements using PageObjectModelSelenium WebDriver - 无法使用 PageObjectModel 访问或单击元素
【发布时间】:2021-06-19 11:55:24
【问题描述】:

我在 Selenium 中使用页面对象模型定义了 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”为空

【问题讨论】:

  • 您正在“@Test”声明之外初始化主页。你需要把它移到里面吗?或者,您是否需要一个“@Before”声明来处理它?
  • 如果我在“@beforeMethod”中初始化主页,主页变量将超出“@Test 方法”的范围。 "@BeforeMethod" public static void beforeM() { HomePage homepage = new HomePage() ; }
  • 然后像我提到的那样把它移到@Test中
  • 感谢为我工作

标签: java selenium object webdriver pageobjects


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-01
      • 2023-03-10
      • 1970-01-01
      • 2021-03-02
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多