0

我在我的 UI 测试中使用 Cucumber 和 Selenide,我有这些方法

public static void initPage(String pageName) throws Exception {
    Set<Class<?>> annotated = new Reflections(PAGES_PACKAGE).getTypesAnnotatedWith(PageTitle.class);

    for (Class classToInit : annotated) {
        PageTitle annotation = (PageTitle) classToInit.getAnnotation(PageTitle.class);
        if (annotation.name().equals(pageName)) {
            classToInit.newInstance();
            lastInitialized = substringAfter(classToInit.toString(), "class ");
            lastInitClass = classToInit;
            return;
        }
    }

    throw new AutotestError("Could not find page to init: " + pageName);
}

public static SelenideElement findElementByTitle(String elementName) throws IllegalAccessException, InstantiationException {
    Set<Field> annotated = new Reflections(lastInitialized, new FieldAnnotationsScanner()).getFieldsAnnotatedWith(ElementTitle.class);

    for (Field field : annotated) {
        ElementTitle annotation = field.getAnnotation(ElementTitle.class);
        if (annotation.name().equals(elementName)) {
            field.setAccessible(true);
            SelenideElement el = (SelenideElement) field
            return el;
        }
    }
    throw new AutotestError("Element not found: " + elementName);
}

我对反射非常陌生,正在尝试使用 org.reflections.Reflections 库构建页面对象模式来搜索各种页面对象类中的注释字段。但是,我在从第二种方法中得到的字段返回 SelenideElement 时遇到问题(行 SelenideElement el = ... 目前完全错误)。如何在我的测试中获得可以用作 SelenideElement(带有 @ElementTitle 和 @FindBy 注释)的字段?提前致谢。

4

2 回答 2

1

您应该将行更改
SelenideElement el = (SelenideElement) field

SelenideElement el = ((SelenideElement) field.get(pageObject))

解释

根据 Field.get 的文档:
在指定对象上返回此字段表示的字段的值。如果该值具有原始类型,则该值会自动包装在对象中。

于 2018-01-16T14:08:20.680 回答
0

我修改了有问题的代码行,如下所示:

SelenideElement el = (SelenideElement) field.get(page(lastInitClass);

如果我理解正确的话,page() 是 com.codeborne.selenide.Selenide.page,它是 Selenium pageFactory 的 Selenide 包装器。

于 2018-01-17T13:34:50.190 回答