Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions docs/Page-objects.md
Original file line number Diff line number Diff line change
Expand Up @@ -763,3 +763,40 @@ It is strongly recommended to implement each subclass of __io.appium.java_clien
super(element);
}
```

## Custom locator annotations

You can define custom `@FindBy`-style locator annotations by meta-annotating your annotation with `@io.appium.java_client.support.PageFactoryFinder` and providing an `AbstractFindByBuilder<T>` implementation:

```java
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
@PageFactoryFinder(DataTestIdBuilder.class)
public @interface DataTestId {
String value() default "";
}

public class DataTestIdBuilder extends AbstractFindByBuilder<DataTestId> {
@Override
public By buildIt(DataTestId annotation, @Nullable Field field) {
String id = annotation.value().isEmpty() && field != null
? field.getName()
: annotation.value();
return By.cssSelector("[data-testid='" + id.replace("'", "\\'") + "']");
}
}
```

### Builder contract

- The builder class referenced by `@PageFactoryFinder` must provide a zero-argument constructor (it does not have to be `public`; the page factory instantiates it reflectively).
- `buildIt(annotation, field)` receives the decorated `Field` when applied to a field, or `null` when resolving a class-level annotation on a `Widget` class.
- Returning `null` from `buildIt` falls back to default lookup resolution (using `ByIdOrName` based on the field or widget class name).
- Only annotations meta-annotated with `io.appium.java_client.support.PageFactoryFinder` are resolved; legacy `org.openqa.selenium.support.PageFactoryFinder` annotations are ignored.

### Combining and overriding annotations

- A `@PageFactoryFinder` annotation supplies the HTML/default locator (`ContentType.HTML_OR_DEFAULT`), so it can be combined on the same field or widget class with mobile native annotations such as `@AndroidFindBy` or `@iOSXCUITFindBy`.
- Combining multiple HTML/default finder annotations (`@FindBy`, `@FindBys`, `@FindAll`, or any `@PageFactoryFinder` annotation) on the same field throws `IllegalArgumentException`. On a `Widget` class, declaring multiple default finder annotations resolves to the first one declared.
- On `Widget` classes, finders declared directly on a subclass override superclass finders (including `@Inherited` custom annotations) instead of conflicting with them. Inherited custom finders from a base widget are used when the subclass declares no finder annotation of its own.

Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,9 @@
import io.appium.java_client.pagefactory.bys.builder.HowToUseSelectors;
import io.appium.java_client.support.ByIdOrName;
import io.appium.java_client.support.CacheLookup;
import io.appium.java_client.support.FindAll;
import io.appium.java_client.support.FindBy;
import io.appium.java_client.support.FindBys;
import io.appium.java_client.support.PageFactory;
import io.appium.java_client.support.pagefactory.ByAll;
import io.appium.java_client.support.pagefactory.internal.PageFactoryFinderSupport;
import org.jspecify.annotations.Nullable;
import org.openqa.selenium.By;

Expand Down Expand Up @@ -91,16 +89,6 @@ public DefaultElementByBuilder(
);
}

private static void checkDisallowedAnnotationPairs(Annotation a1, Annotation a2)
throws IllegalArgumentException {
if (a1 != null && a2 != null) {
throw new IllegalArgumentException(
"If you use a '@" + a1.getClass().getSimpleName() + "' annotation, "
+ "you must not also use a '@" + a2.getClass().getSimpleName()
+ "' annotation");
}
}

private static By buildMobileBy(LocatorGroupStrategy locatorGroupStrategy, By[] bys) {
if (bys.length == 0) {
return null;
Expand All @@ -114,38 +102,17 @@ private static By buildMobileBy(LocatorGroupStrategy locatorGroupStrategy, By[]
@Override
protected void assertValidAnnotations() {
AnnotatedElement annotatedElement = annotatedElementContainer.getAnnotated();
FindBy findBy = SeleniumAnnotationsCompat.find(annotatedElement, FindBy.class);
FindBys findBys = SeleniumAnnotationsCompat.find(annotatedElement, FindBys.class);
checkDisallowedAnnotationPairs(findBy, findBys);
FindAll findAll = SeleniumAnnotationsCompat.find(annotatedElement, FindAll.class);
checkDisallowedAnnotationPairs(findBy, findAll);
checkDisallowedAnnotationPairs(findBys, findAll);
if (annotatedElement != null) {
PageFactoryFinderSupport.validateFinderAnnotations(annotatedElement);
}
}

@Override
protected By buildDefaultBy() {
AnnotatedElement annotatedElement = annotatedElementContainer.getAnnotated();
Field field = annotatedElement instanceof Field ? (Field) annotatedElement : null;
By defaultBy = null;
FindBy findBy = SeleniumAnnotationsCompat.find(annotatedElement, FindBy.class);
if (findBy != null) {
defaultBy = new FindBy.FindByBuilder().buildIt(findBy, field);
}

if (defaultBy == null) {
FindBys findBys = SeleniumAnnotationsCompat.find(annotatedElement, FindBys.class);
if (findBys != null) {
defaultBy = new FindBys.FindByBuilder().buildIt(findBys, field);
}
}

if (defaultBy == null) {
FindAll findAll = SeleniumAnnotationsCompat.find(annotatedElement, FindAll.class);
if (findAll != null) {
defaultBy = new FindAll.FindByBuilder().buildIt(findAll, field);
}
}
return defaultBy;
return annotatedElement != null
? PageFactoryFinderSupport.buildBy(annotatedElement, annotatedElement instanceof Field)
: null;
}

private By[] getBys(Class<? extends Annotation> singleLocator, Class<? extends Annotation> chainedLocator,
Expand Down Expand Up @@ -310,7 +277,8 @@ protected By buildMobileNativeBy() {
@Override
public boolean isLookupCached() {
AnnotatedElement annotatedElement = annotatedElementContainer.getAnnotated();
return SeleniumAnnotationsCompat.isPresent(annotatedElement, CacheLookup.class);
return annotatedElement != null
&& PageFactoryFinderSupport.isCompatibleAnnotationPresent(annotatedElement, CacheLookup.class);
}

private By returnMappedBy(By byDefault, By nativeAppBy) {
Expand Down
1 change: 1 addition & 0 deletions src/main/java/io/appium/java_client/support/FindAll.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
@PageFactoryFinder(FindAll.FindByBuilder.class)
public @interface FindAll {
/**
* The locators to search with.
Expand Down
1 change: 1 addition & 0 deletions src/main/java/io/appium/java_client/support/FindBy.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
@PageFactoryFinder(FindBy.FindByBuilder.class)
public @interface FindBy {
/**
* The location strategy to use together with {@link #using()}.
Expand Down
1 change: 1 addition & 0 deletions src/main/java/io/appium/java_client/support/FindBys.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
@PageFactoryFinder(FindBys.FindByBuilder.class)
public @interface FindBys {
/**
* The locators to chain.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.appium.java_client.support;
Comment thread
mykola-mokhnach marked this conversation as resolved.
Resolved

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** Marks a custom locator annotation with its builder class. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface PageFactoryFinder {
/**
* Specify the builder implementation used to construct a locator from the annotated type.
*
* @return the builder class
*/
Class<? extends AbstractFindByBuilder<?>> value();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.appium.java_client.support.pagefactory;

import io.appium.java_client.support.ByIdOrName;
import io.appium.java_client.support.CacheLookup;
import io.appium.java_client.support.pagefactory.internal.PageFactoryFinderSupport;
import org.openqa.selenium.By;

import java.lang.reflect.Field;

import static java.util.Objects.requireNonNull;

/**
* Processes locator and cache annotations on a page object field.
*
* <p>Selenium's protected {@code AbstractAnnotations} hooks ({@code buildByFromFindBy},
* {@code buildByFromShortFindBy}, {@code buildByFromLongFindBy}, {@code assertValidFindBys},
* and {@code assertValidFindAll}) are intentionally omitted because finder resolution and
* conflict validation are centralized in {@link PageFactoryFinderSupport} via
* {@link io.appium.java_client.support.PageFactoryFinder} and
* {@link io.appium.java_client.support.AbstractFindByBuilder}.
*/
public class Annotations extends AbstractAnnotations {
private final Field field;

/**
* Creates an annotation processor for the given field.
*
* @param field the field to inspect
*/
public Annotations(Field field) {
this.field = requireNonNull(field, "Field must not be null");
}

@Override
public boolean isLookupCached() {
return PageFactoryFinderSupport.isCompatibleAnnotationPresent(field, CacheLookup.class);
}

@Override
public By buildBy() {
Comment thread
mykola-mokhnach marked this conversation as resolved.
Resolved
assertValidAnnotations();

By ans = PageFactoryFinderSupport.buildBy(field);
if (ans == null) {
ans = buildByFromDefault();
}
return ans;
}

/**
* Gets the annotated field handled by this instance.
*
* @return the field
*/
protected Field getField() {
return field;
}

/**
* Builds the fallback locator when no locator annotation produces one.
*
* @return a locator using the field name
*/
protected By buildByFromDefault() {
return new ByIdOrName(field.getName());
}

/** Verifies that mutually exclusive locator annotations are not combined on the field. */
protected void assertValidAnnotations() {
PageFactoryFinderSupport.validateFinderAnnotations(field);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,10 @@

package io.appium.java_client.support.pagefactory;

import io.appium.java_client.support.FindAll;
import io.appium.java_client.support.FindBy;
import io.appium.java_client.support.FindBys;
import io.appium.java_client.support.PageFactory;
import io.appium.java_client.support.pagefactory.internal.LocatingElementHandler;
import io.appium.java_client.support.pagefactory.internal.LocatingElementListHandler;
import io.appium.java_client.support.pagefactory.internal.PageFactoryFinderSupport;
import org.jspecify.annotations.Nullable;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WrapsElement;
Expand All @@ -39,8 +37,9 @@

/**
* Default decorator for use with PageFactory. Will decorate 1) all the WebElement fields and 2)
* {@code List<WebElement>} fields that have {@code @FindBy}, {@code @FindBys}, or {@code @FindAll}
* annotation with a proxy that locates the elements using the passed in ElementLocatorFactory.
* {@code List<WebElement>} fields that have {@code @FindBy}, {@code @FindBys}, {@code @FindAll},
* or another Appium {@code @PageFactoryFinder} annotation with a proxy that locates the elements
* using the passed in ElementLocatorFactory.
* Adapted from Selenium's {@code org.openqa.selenium.support.pagefactory.DefaultFieldDecorator}
* (Apache License 2.0).
*/
Expand Down Expand Up @@ -106,13 +105,11 @@ private boolean isDecoratableList(Field field, @Nullable Class<?> pageClass) {
return false;
}

return hasStandardLocatorAnnotation(field);
return hasLocatorAnnotation(field);
}

private static boolean hasStandardLocatorAnnotation(Field field) {
return field.getAnnotation(FindBy.class) != null
|| field.getAnnotation(FindBys.class) != null
|| field.getAnnotation(FindAll.class) != null;
private static boolean hasLocatorAnnotation(Field field) {
return PageFactoryFinderSupport.hasAppiumLocatorAnnotation(field);
}

/**
Expand Down
Loading
Loading