我使用 Cucumber 和 Selenide 进行 UI 测试,我有这些方法
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 注释)的字段?提前致谢。
最佳答案
你应该换线
SelenideElement el = (SelenideElement) 字段
到
SelenideElement el = ((SelenideElement) field.get(pageObject))
说明
根据 Field.get 的文档:
返回指定对象上此 Field 表示的字段的值。如果该值具有基本类型,则该值会自动包装在对象中。
关于Java反射方法获取带注释的字段作为SelenideElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48282645/