com.oakfusion.polonium.PageFragmentFactory Maven / Gradle / Ivy
The newest version!
package com.oakfusion.polonium;
import com.oakfusion.polonium.config.PoloniumConfig;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import com.oakfusion.polonium.annotations.PageFragment;
import java.lang.reflect.Field;
public class PageFragmentFactory {
private final Class> testClass;
private final WebDriver driver;
private PoloniumConfig poloniumConfig;
public PageFragmentFactory(Class> testClass, WebDriver driver, PoloniumConfig poloniumConfig) {
this.testClass = testClass;
this.driver = driver;
this.poloniumConfig = poloniumConfig;
}
public void injectPagesIntoTestClassFields(Object testClassInstance) {
for(Field testClassField : testClass.getDeclaredFields()) {
if(testClassField.isAnnotationPresent(PageFragment.class)) {
Class> pageClass = testClassField.getType();
if (BasePageFragment.class.isAssignableFrom(pageClass)) {
@SuppressWarnings("unchecked")
BasePageFragment page = createPageInstance((Class extends BasePageFragment>)pageClass);
injectPage(testClassField, page, testClassInstance);
} else {
throw new RuntimeException(pageClass + "do not extends " + BasePageFragment.class);
}
}
}
}
public T createPageInstance(Class pageClass) {
T page = PageFactory.initElements(driver, pageClass);
String url = getUrlFromAnnotatedClass(pageClass);
page.setUrl(url);
page.setDriver(driver);
page.setPageFragmentFactory(this);
return page;
}
private String getUrlFromAnnotatedClass(Class> pageClass) {
PageFragment pageFragment = pageClass.getAnnotation(PageFragment.class);
final String url = pageFragment.url();
if (poloniumConfig.hasHost() && url.startsWith("/")) {
return poloniumConfig.getHost() + url;
}
return url;
}
private void injectPage(Field testClassField, BasePageFragment page, Object testClassInstance) {
try {
testClassField.setAccessible(true);
testClassField.set(testClassInstance, page);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}