当前位置: 首页 > 知识库问答 >
问题:

@FindBy注释定义的Webelement返回空指针

岳时铭
2023-03-14

由于某种原因,当我调用方法Spage.editExButton(int ID)时,我得到一个错误,说WebElement first为null。为什么是null?我已经使用@FindBy注释定义了它。我必须使用findElement(By.id("xxx "))显式定义元素,以便能够单击它。但是为什么我不能用@FindBy符号来调用它呢?

public class SPage extends GPage<SPage> {

    public SPage() {
        super();
    }

    public SPage(String pageType) {
        super(pageType);
    }

    @FindBy(id = "xxx")
    WebElement first;

    public WebElement eButton(int ID) {
        first.click();
        String tmp = ID + "-Edit";
        WebElement edit = getDriver().findElement(By.id(tmp));
        return edit;
    }

    public EPage cEdit(int ID) {
        eButton(ID).click();
        return new EPage(getBasePageType()).openPage(EPage.class);
    }
}

我这样调用方法:

static EPage epage;
static SPage spage;

@Test
public void edit_exception() {
             epage = spage.cEdit(IDbefore);
}

共有3个答案

西门骁
2023-03-14

在我的测试课中,我添加了以下代码行

WebMainMenu mainmenu = PageFactory.initElements(driver, WebMainMenu.class);

mainmenu.doStuff(驱动程序,5);

我同意如上所述,您需要实例化页面对象

吴俊晤
2023-03-14

因为所有其他答案都提到我们必须使用< code > page factory . init elements()初始化webElements,

有两种方法可以做到这一点,或者更确切地说,有两个地方可以做到这一点:

1)内部类SPage:

由于SPage类中有两个构造函数,因此我们必须添加以下代码来初始化该类中声明的所有元素,这应该在两个类中完成,因为我们不知道将使用哪个构造函数来初始化SPage:

我们将驱动程序实例传递给 SPage 类构造函数,如下所示:

public SPage(WebDriver driver) {
    super();
    PageFactory.initElements(driver, this);
}

public SPage(String pageType, WebDriver driver) {
    super(pageType);
    PageFactory.initElements(driver, this);
}

2)在要使用SPage WebElements的其他类中:

在上面的示例元素中可以在编写edit_exception()方法的类中初始化,简而言之,在任何地方之前,我们都想使用类SPage的元素/操作,现在代码将如下所示:

@Test
public void edit_exception() {
             spage =  PageFactory.initElements(driver, SPage.class);  //we are not passing driver instance to SPage class
             epage = spage.cEdit(IDbefore);
}
孟德曜
2023-03-14

您需要调用这个(最好在您的构造函数中):

PageFactory.initElements(getDriver(), this);

更多信息:https://code.google.com/p/selenium/wiki/PageFactory

 类似资料:
  • 我正在学习《棱角2》。 我希望使用@ViewChild注释从父组件访问子组件。 这里有几行代码: 在BodyContent.TS我有: 在filtertiles.ts中时: 最后,这里是模板(如注释中所建议的): BodyContent.html filtertiles.html html模板被正确加载到ico-filter-tiles标记中(确实我能够看到标题)。 注意:使用DynamicCom

  • 在python 3.x中,通常使用函数的返回类型注释,例如: “void”类型的正确注释是什么? 我正在考虑三种选择:

  • 我在一个使用Selenium和C#的自动化项目中工作。我使用Page Object模式定义每个页面(带有它们的定位器),然后在一个测试类中分别定义测试。我有一个Page类,它是页面的基类,我在其中调用:PageFactory.initElements(webDriver,this); 并定义所有页面的通用方法。然后每个页面从page继承,并使用@findby注释定义相应的元素: 添加了一个新的登录

  • 我有一个包含2列store_number和manager_id的表,我为这个表创建了一个实体和一个存储库类。 它返回一个空列表,但是当我直接执行上面的查询时,我会得到结果。 请帮我做这个。我在这里做错什么了吗?

  • 我有以下块,在该块中,我期待来自的方法的响应: 我期待的响应类型为,请求正确执行,状态为200OK,但是模型的所有字段都为null,因此我从REST调用接收的响应没有被绑定(映射)。的必填字段注释为:

  • 我使用注释在selenium java中声明webelement。在大多数情况下,我有简单的定位器: 但是有时我需要将变量传递到xpath或任何其他定位器。在这种情况下,我不声明webelement之前,而是在函数中: 我不喜欢它,因为定位器应该在一个地方被调用,而不是与代码可见性的函数混合 我想做这样的事情: 然后呢 你有什么解决办法吗?