Closed mahesht36 closed 5 years ago
defaultTasks 'clean', 'test', 'serenity:aggregate'
repositories { mavenCentral() jcenter() }
buildscript { repositories { mavenLocal() jcenter() } dependencies { classpath("net.serenity-bdd:serenity-gradle-plugin:1.9.12") } }
apply plugin: 'idea' apply plugin: 'java' apply plugin: 'net.serenity-bdd.aggregator'
sourceCompatibility = 1.8
dependencies {
compile group: 'net.serenity-bdd', name: 'serenity-rest-assured', version: '1.9.25'
compile group: 'net.serenity-bdd', name: 'serenity-core', version: '1.9.12'
compile group: 'net.serenity-bdd', name: 'serenity-cucumber', version: '1.9.5'
compile group: 'net.serenity-bdd', name: 'serenity-junit', version: '1.9.12'
compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
compile group: 'com.mashape.unirest', name: 'unirest-java', version: '1.4.9'
compile group: 'com.jayway.jsonpath', name: 'json-path', version: '2.2.0'
compile group: 'javax', name: 'javaee-api', version: '7.0'
compile group: 'org.simplejavamail', name: 'simple-java-mail', version: '4.1.2'
compile group: 'com.google.code.gson', name: 'gson', version: '2.7'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.0.1'
compile group: 'io.github.bonigarcia', name: 'webdrivermanager', version: '3.4.0'
compile group: 'javax.mail', name: 'javax.mail-api', version: '1.6.0'
compile 'com.microsoft.sqlserver:mssql-jdbc:6.1.0.jre8'
compile group: 'ch.qos.logback', name: 'logback-core', version: '1.2.3'
test {
testLogging.showStandardStreams = true
systemProperties System.getProperties()
}
} gradle.startParameter.continueOnFailure = true
WrongPageError
means Serenity was unable to instantiate your page object; possibly because the constructor is not as expected, or that some exception is thrown during the creation process.
Hi , I am not getting you point,very new to this gradle and cucumber. If you have time can we connect over Skype. Mahesht88
If you post your Page Object class there might be something easy to spot. Otherwise you can ask the Serenity community on https://serenity-bdd.rocket.chat, or if your question is urgent, you can find some commercial support options here: https://johnfergusonsmart.com/serenity-bdd-mentoring/
package net.thucydides.core.pages;
import com.google.common.base.Predicate; import org.openqa.selenium.WebDriver;
public abstract class PageObject extends net.serenitybdd.core.pages.PageObject {
protected PageObject() {
super();
}
protected PageObject(WebDriver driver, Predicate<? super net.serenitybdd.core.pages.PageObject> callback) {
super(driver, callback);
}
public PageObject(WebDriver driver, int ajaxTimeout) {
super(driver, ajaxTimeout);
}
public PageObject(WebDriver driver) {
super(driver);
}
}
package net.serenitybdd.core.pages;
import com.google.common.base.Predicate; import com.paulhammant.ngwebdriver.NgWebDriver; import net.serenitybdd.core.collect.NewList; import net.thucydides.core.ThucydidesSystemProperty; import net.thucydides.core.annotations.WhenPageOpens; import net.thucydides.core.fluent.ThucydidesFluentAdapter; import net.thucydides.core.guice.Injectors; import net.thucydides.core.pages.Pages; import net.thucydides.core.pages.WrongPageError; import net.thucydides.core.pages.components.Dropdown; import net.thucydides.core.pages.components.FileToUpload; import net.thucydides.core.pages.jquery.JQueryEnabledPage; import net.thucydides.core.reflection.MethodFinder; import net.thucydides.core.scheduling.FluentWaitWithRefresh; import net.thucydides.core.scheduling.NormalFluentWait; import net.thucydides.core.scheduling.ThucydidesFluentWait; import net.thucydides.core.steps.PageObjectStepDelayer; import net.thucydides.core.steps.StepEventBus; import net.thucydides.core.steps.WaitForBuilder; import net.thucydides.core.util.EnvironmentVariables; import net.thucydides.core.util.Inflector; import net.thucydides.core.webdriver.; import net.thucydides.core.webdriver.javascript.JavascriptExecutorFacade; import net.thucydides.core.webelements.Checkbox; import net.thucydides.core.webelements.RadioButtonGroup; import org.apache.commons.lang3.StringUtils; import org.openqa.selenium.; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.temporal.TemporalUnit; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MINUTES; import static net.serenitybdd.core.selectors.Selectors.xpathOrCssSelector; import static net.thucydides.core.ThucydidesSystemProperty.THUCYDIDES_JQUERY_INTEGRATION; import static net.thucydides.core.ThucydidesSystemProperty.WEBDRIVER_TIMEOUTS_FLUENTWAIT; import static net.thucydides.core.ThucydidesSystemProperty.WEBDRIVER_WAIT_FOR_TIMEOUT; import static net.thucydides.core.webdriver.javascript.JavascriptSupport.javascriptIsSupportedIn;
/**
@author johnsmart */ public abstract class PageObject {
private static final int WAIT_FOR_ELEMENT_PAUSE_LENGTH = 250;
private static final Logger LOGGER = LoggerFactory.getLogger(PageObject.class);
private WebDriver driver;
private Pages pages;
private MatchingPageExpressions matchingPageExpressions;
private RenderedPageObjectView renderedView;
private PageUrls pageUrls;
private net.serenitybdd.core.time.SystemClock clock;
private Duration waitForTimeout; private Duration waitForElementTimeout;
private final Sleeper sleeper; private final Clock webdriverClock; private JavascriptExecutorFacade javascriptExecutorFacade;
private EnvironmentVariables environmentVariables;
public void setImplicitTimeout(int duration, TemporalUnit unit) {
waitForElementTimeout = Duration.of(duration, unit);
setDriverImplicitTimeout(waitForElementTimeout);
}
private void setDriverImplicitTimeout(Duration implicitTimeout) { if (driver instanceof ConfigurableTimeouts) { ((ConfigurableTimeouts) driver).setImplicitTimeout(implicitTimeout); } else { driver.manage().timeouts().implicitlyWait(implicitTimeout.toMillis(), MILLISECONDS); } }
public void resetImplicitTimeout() { if (driver instanceof ConfigurableTimeouts) { waitForElementTimeout = ((ConfigurableTimeouts) driver).resetTimeouts(); } else { waitForElementTimeout = getDefaultImplicitTimeout(); driver.manage().timeouts().implicitlyWait(waitForElementTimeout.toMillis(), MILLISECONDS); } }
private Duration getDefaultImplicitTimeout() { Integer configuredTimeout = ThucydidesSystemProperty.WEBDRIVER_TIMEOUTS_IMPLICITLYWAIT.integerFrom(environmentVariables); return Duration.ofMillis(configuredTimeout); }
private enum OpenMode { CHECK_URL_PATTERNS, IGNORE_URL_PATTERNS }
protected PageObject() { this.webdriverClock = new SystemClock(); this.clock = Injectors.getInjector().getInstance(net.serenitybdd.core.time.SystemClock.class); this.environmentVariables = Injectors.getInjector().getProvider(EnvironmentVariables.class).get(); this.sleeper = Sleeper.SYSTEM_SLEEPER; setupPageUrls(); }
protected PageObject(final WebDriver driver, Predicate<? super PageObject> callback) { this(); this.driver = driver; callback.apply(this); }
public PageObject(final WebDriver driver, final int ajaxTimeout) { this(); setDriver(driver, ajaxTimeout); }
public PageObject(final WebDriver driver) { this(); ThucydidesWebDriverSupport.useDriver(driver); setDriver(driver); }
public PageObject(final WebDriver driver, final EnvironmentVariables environmentVariables) { this(); this.environmentVariables = environmentVariables; setDriver(driver); }
protected void setDriver(WebDriver driver, long timeout) { this.driver = driver; new DefaultPageObjectInitialiser(driver, timeout).apply(this); }
public
public
public Duration getWaitForTimeout() {
if (waitForTimeout == null) {
int configuredWaitForTimeoutInMilliseconds =fluentWaitTimeout();
waitForTimeout = Duration.ofMillis(configuredWaitForTimeoutInMilliseconds);
}
return waitForTimeout;
}
private int fluentWaitTimeout() { return (WEBDRIVER_WAIT_FOR_TIMEOUT.integerFrom(environmentVariables, WEBDRIVER_TIMEOUTS_FLUENTWAIT.integerFrom(environmentVariables, (int) DefaultTimeouts.DEFAULT_WAIT_FOR_TIMEOUT.toMillis()))); }
@Deprecated public Duration getWaitForElementTimeout() { return getImplicitWaitTimeout(); }
public Duration getImplicitWaitTimeout() {
if (waitForElementTimeout == null) {
int configuredWaitForTimeoutInMilliseconds =
ThucydidesSystemProperty.WEBDRIVER_TIMEOUTS_IMPLICITLYWAIT
.integerFrom(environmentVariables, (int) DefaultTimeouts.DEFAULT_IMPLICIT_WAIT_TIMEOUT.toMillis());
waitForElementTimeout = Duration.ofMillis(configuredWaitForTimeoutInMilliseconds);
}
return waitForElementTimeout;
}
public void setPages(Pages pages) { this.pages = pages; }
public
return pages.getPage(pageObjectClass);
}
/**
public FileToUpload uploadData(String data) throws IOException { Path datafile = Files.createTempFile("upload", "data"); Files.write(datafile, data.getBytes(StandardCharsets.UTF_8)); return new FileToUpload(driver, datafile.toAbsolutePath().toString()).useRemoteDriver(isDefinedRemoteUrl()); }
public FileToUpload uploadData(byte[] data) throws IOException { Path datafile = Files.createTempFile("upload", "data"); Files.write(datafile, data); return new FileToUpload(driver, datafile.toAbsolutePath().toString()).useRemoteDriver(isDefinedRemoteUrl()); }
private boolean isDefinedRemoteUrl() { boolean isRemoteUrl = ThucydidesSystemProperty.WEBDRIVER_REMOTE_URL.isDefinedIn(environmentVariables); boolean isSaucelabsUrl = ThucydidesSystemProperty.SAUCELABS_URL.isDefinedIn(environmentVariables); boolean isBrowserStack = ThucydidesSystemProperty.BROWSERSTACK_URL.isDefinedIn(environmentVariables); return isRemoteUrl || isSaucelabsUrl || isBrowserStack; }
private void setupPageUrls() { setPageUrls(new PageUrls(this)); }
/**
public void setWaitForTimeout(final long waitForTimeoutInMilliseconds) { this.waitForTimeout = Duration.ofMillis(waitForTimeoutInMilliseconds); getRenderedView().setWaitForTimeout(this.waitForTimeout); }
public void setWaitForElementTimeout(final long waitForTimeoutInMilliseconds) { this.waitForElementTimeout = Duration.ofMillis(waitForTimeoutInMilliseconds); }
protected RenderedPageObjectView getRenderedView() { if (renderedView == null) { renderedView = new RenderedPageObjectView(driver, this, getWaitForTimeout(), true); } return renderedView; }
protected net.serenitybdd.core.time.SystemClock getClock() { return clock; }
private MatchingPageExpressions getMatchingPageExpressions() { if (matchingPageExpressions == null) { matchingPageExpressions = new MatchingPageExpressions(this); } return matchingPageExpressions; }
public WebDriver getDriver() { return driver; }
public String getTitle() { return driver.getTitle(); }
public boolean matchesAnyUrl() { return thereAreNoPatternsDefined(); }
/**
private boolean matchUrlAgainstEachPattern(final String currentUrl) { return getMatchingPageExpressions().matchUrlAgainstEachPattern(currentUrl); }
private boolean thereAreNoPatternsDefined() { return getMatchingPageExpressions().isEmpty(); }
public PageObject waitForRenderedElements(final By byElementCriteria) { getRenderedView().waitFor(byElementCriteria); return this; }
/**
public RenderedPageObjectView withTimeoutOf(int timeout, TemporalUnit units) { return withTimeoutOf(Duration.of(timeout, units)); }
public RenderedPageObjectView withTimeoutOf(Duration timeout) { return new RenderedPageObjectView(driver, this, timeout, false); }
public PageObject waitFor(String xpathOrCssSelector) { return waitForRenderedElements(xpathOrCssSelector(xpathOrCssSelector)); }
public PageObject waitFor(ExpectedCondition expectedCondition) { getRenderedView().waitFor(expectedCondition); return this; }
public PageObject waitForRenderedElementsToBePresent(final By byElementCriteria) { getRenderedView().waitForPresenceOf(byElementCriteria);
return this;
}
public PageObject waitForPresenceOf(String xpathOrCssSelector) { return waitForRenderedElementsToBePresent(xpathOrCssSelector(xpathOrCssSelector)); }
public PageObject waitForRenderedElementsToDisappear(final By byElementCriteria) { getRenderedView().waitForElementsToDisappear(byElementCriteria); return this; }
public PageObject waitForAbsenceOf(String xpathOrCssSelector) { return waitForRenderedElementsToDisappear(xpathOrCssSelector(xpathOrCssSelector)); }
/**
public PageObject waitForTitleToAppear(final String expectedTitle) { waitOnPage().until(ExpectedConditions.titleIs(expectedTitle)); return this; }
private WebDriverWait waitOnPage() { return new WebDriverWait(driver, getWaitForTimeout().getSeconds()); // waitForTimeoutInSecondsWithAMinimumOfOneSecond()); }
public PageObject waitForTitleToDisappear(final String expectedTitle) { getRenderedView().waitForTitleToDisappear(expectedTitle); return this; }
/**
private boolean driverIsDisabled() { return StepEventBus.getEventBus().webdriverCallsAreSuspended(); }
/**
private ExpectedCondition
public PageObject waitForTextToDisappear(final String expectedText) { return waitForTextToDisappear(expectedText, getWaitForTimeout().toMillis()); }
/**
Waits for a given text to not be anywhere on the page. */ public PageObject waitForTextToDisappear(final String expectedText, final long timeoutInMilliseconds) {
getRenderedView().waitForTextToDisappear(expectedText, timeoutInMilliseconds); return this; }
/**
Waits for a given text to appear anywhere on the page. */ public PageObject waitForTextToAppear(final String expectedText, final long timeout) {
getRenderedView().waitForTextToAppear(expectedText, timeout); return this; }
/**
public PageObject waitForAnyTextToAppear(final WebElement element, final String... expectedText) { getRenderedView().waitForAnyTextToAppear(element, expectedText); return this; }
/**
public PageObject waitForAnyRenderedElementOf(final By... expectedElements) { getRenderedView().waitForAnyRenderedElementOf(expectedElements); return this; }
protected void waitABit(final long timeInMilliseconds) { getClock().pauseFor(timeInMilliseconds); }
public WaitForBuilder<? extends PageObject> waitFor(int duration) { return new PageObjectStepDelayer(clock, this).waitFor(duration); }
public List
public
/**
/**
/**
/*
/*
/**
/**
public void selectFromDropdown(final WebElement dropdown, final String visibleLabel) {
Dropdown.forWebElement(dropdown).select(visibleLabel);
notifyScreenChange();
}
public void selectMultipleItemsFromDropdown(final WebElement dropdown, final String... selectedLabels) { Dropdown.forWebElement(dropdown).selectMultipleItems(selectedLabels); notifyScreenChange(); }
public Set
public Set
public String getSelectedValueFrom(final WebElement dropdown) { return Dropdown.forWebElement(dropdown).getSelectedValue(); }
public String getSelectedLabelFrom(final WebElement dropdown) { return Dropdown.forWebElement(dropdown).getSelectedLabel(); }
public void setCheckbox(final WebElement field, final boolean value) { Checkbox checkbox = new Checkbox(field); checkbox.setChecked(value); notifyScreenChange(); }
public boolean containsText(final String textValue) { return getRenderedView().containsText(textValue); }
/**
/**
public void shouldBeVisible(final By byCriteria) { waitOnPage().until(ExpectedConditions.visibilityOfElementLocated(byCriteria)); }
public void shouldNotBeVisible(final WebElement field) { try { element(field).shouldNotBeVisible(); } catch (NoSuchElementException e) { // A non-existant element is not visible } }
public void shouldNotBeVisible(final By byCriteria) {
List
private long waitForTimeoutInSecondsWithAMinimumOfOneSecond() { return (getWaitForTimeout().getSeconds() < 1) ? 1 : (getWaitForTimeout().getSeconds()); }
public long waitForTimeoutInMilliseconds() { return getWaitForTimeout().toMillis(); }
public long implicitTimoutMilliseconds() { return getImplicitWaitTimeout().toMillis(); }
public String updateUrlWithBaseUrlIfDefined(final String startingUrl) {
String baseUrl = pageUrls.getSystemBaseUrl();
if ((baseUrl != null) && (!StringUtils.isEmpty(baseUrl))) {
return replaceHost(startingUrl, baseUrl);
} else {
return startingUrl;
}
}
private String replaceHost(final String starting, final String base) {
String updatedUrl = starting;
try {
URL startingUrl = new URL(starting);
URL baseUrl = new URL(base);
String startingHostComponent = hostComponentFrom(startingUrl.getProtocol(),
startingUrl.getHost(),
startingUrl.getPort());
String baseHostComponent = hostComponentFrom(baseUrl.getProtocol(),
baseUrl.getHost(),
baseUrl.getPort());
updatedUrl = starting.replaceFirst(startingHostComponent, baseHostComponent);
} catch (MalformedURLException e) {
LOGGER.error("Failed to analyse default page URL: Starting URL: {}, Base URL: {}", starting, base);
LOGGER.error("URL analysis failed with exception:", e);
}
return updatedUrl;
}
private String hostComponentFrom(final String protocol, final String host, final int port) { StringBuilder hostComponent = new StringBuilder(protocol); hostComponent.append("://"); hostComponent.append(host); if (port > 0) { hostComponent.append(":"); hostComponent.append(port); } return hostComponent.toString(); }
/**
/**
private void open(final OpenMode openMode, final String... parameterValues) { String startingUrl = pageUrls.getStartingUrl(parameterValues); LOGGER.debug("Opening page at url {}", startingUrl); openPageAtUrl(startingUrl); checkUrlPatterns(openMode); initializePage(); LOGGER.debug("Page opened"); }
public final void open(final String urlTemplateName, final String[] parameterValues) { open(OpenMode.CHECK_URL_PATTERNS, urlTemplateName, parameterValues); }
/**
private void open(final OpenMode openMode, final String urlTemplateName, final String[] parameterValues) { String startingUrl = pageUrls.getNamedUrl(urlTemplateName, parameterValues); LOGGER.debug("Opening page at url {}", startingUrl); openPageAtUrl(startingUrl); checkUrlPatterns(openMode); initializePage(); LOGGER.debug("Page opened"); }
/**
/**
private void open(final OpenMode openMode) { String startingUrl = updateUrlWithBaseUrlIfDefined(pageUrls.getStartingUrl()); openPageAtUrl(startingUrl); checkUrlPatterns(openMode); initializePage(); }
private void initializePage() { addJQuerySupport(); callWhenPageOpensMethods(); }
private void checkUrlPatterns(final OpenMode openMode) { if (openMode == OpenMode.CHECK_URL_PATTERNS) { ensurePageIsOnAMatchingUrl(); } }
private void ensurePageIsOnAMatchingUrl() { if (!matchesAnyUrl()) { String currentUrl = getDriver().getCurrentUrl(); if (!compatibleWithUrl(currentUrl)) { thisIsNotThePageYourLookingFor(); } } }
/**
private void thisIsNotThePageYourLookingFor() {
String errorDetails = "This is not the page you're looking for: "
+ "I was looking for a page compatible with " + this.getClass() + " but "
+ "I was at the URL " + getDriver().getCurrentUrl();
throw new WrongPageError(errorDetails);
}
final public void openAt(String relativeUrl) { openPageAtUrl(updateUrlWithBaseUrlIfDefined(relativeUrl)); callWhenPageOpensMethods(); }
final public void openUrl(String absoluteUrl) { openPageAtUrl(absoluteUrl); callWhenPageOpensMethods(); }
/**
Override this method */ public void callWhenPageOpensMethods() { if (StepEventBus.getEventBus().currentTestIsSuspended()) { return; }
for (Method annotatedMethod : methodsAnnotatedWithWhenPageOpens()) { try { annotatedMethod.setAccessible(true); annotatedMethod.invoke(this); } catch (Throwable e) { LOGGER.error("Could not execute @WhenPageOpens annotated method: " + e.getMessage()); if (e instanceof InvocationTargetException) { e = ((InvocationTargetException) e).getTargetException(); } if (AssertionError.class.isAssignableFrom(e.getClass())) { throw (AssertionError) e; } else { throw new UnableToInvokeWhenPageOpensMethods("Could not execute @WhenPageOpens annotated method: "
private List
public static String[] withParameters(final String... parameterValues) { return parameterValues; }
private void openPageAtUrl(final String startingUrl) { getDriver().get(startingUrl); if (javascriptIsSupportedIn(getDriver())) { addJQuerySupport(); } }
public void clickOn(final WebElement webElement) { element(webElement).click(); }
/**
public void setDefaultBaseUrl(final String defaultBaseUrl) { pageUrls.overrideDefaultBaseUrl(defaultBaseUrl); }
/**
public void blurActiveElement() { getJavascriptExecutorFacade().executeScript("document.activeElement.blur();"); }
protected JavascriptExecutorFacade getJavascriptExecutorFacade() { if (javascriptExecutorFacade == null) { javascriptExecutorFacade = new JavascriptExecutorFacade(driver); } return javascriptExecutorFacade; }
/**
private String nameOf(WebElement webElement) { try { return webElement.toString(); } catch (Exception e) { return "Unknown web element"; } }
public
public
/**
public
public
public List
List<WebElement> matchingWebElements = driver.findElements(bySelector);
List<WebElementFacade> allElements = new ArrayList<>();
for (WebElement matchingElement : matchingWebElements) {
allElements.add($(matchingElement));
}
return allElements;
}
/**
public
public List
public boolean containsElements(By bySelector) { return !findAll(bySelector).isEmpty(); }
public boolean containsElements(String xpathOrCssSelector) { return !findAll(xpathOrCssSelector).isEmpty(); }
public Object evaluateJavascript(final String script) { addJQuerySupport(); JavascriptExecutorFacade js = new JavascriptExecutorFacade(driver); return js.executeScript(script); }
public Object evaluateJavascript(final String script, final Object... params) { addJQuerySupport(); JavascriptExecutorFacade js = new JavascriptExecutorFacade(driver); return js.executeScript(script, params); }
public void addJQuerySupport() { if (pageIsLoaded() && jqueryIntegrationIsActivated() && driverIsJQueryCompatible()) { JQueryEnabledPage jQueryEnabledPage = JQueryEnabledPage.withDriver(getDriver()); jQueryEnabledPage.activateJQuery(); } }
protected boolean driverIsJQueryCompatible() { try { if (getDriver() instanceof WebDriverFacade) { return SupportedWebDriver.forClass(((WebDriverFacade) getDriver()).getDriverClass()) .supportsJavascriptInjection(); } return SupportedWebDriver.forClass(getDriver().getClass()).supportsJavascriptInjection(); } catch (IllegalArgumentException probablyAMockedDriver) { return false; } }
private Boolean jqueryIntegrationIsActivated() { return THUCYDIDES_JQUERY_INTEGRATION.booleanFrom(environmentVariables, true); }
public RadioButtonGroup inRadioButtonGroup(String name) { return new RadioButtonGroup(getDriver().findElements(By.name(name))); }
private boolean pageIsLoaded() { try { return (driverIsInstantiated() && getDriver().getCurrentUrl() != null); } catch (WebDriverException e) { return false; } }
protected boolean driverIsInstantiated() { if (getDriver() instanceof WebDriverFacade) { return ((WebDriverFacade) getDriver()).isEnabled() && ((WebDriverFacade) getDriver()).isInstantiated(); } return true; }
public ThucydidesFluentWait
public ThucydidesFluentWait
public WebElementFacade waitFor(WebElement webElement) { return getRenderedView().waitFor(webElement); }
public WebElementFacade waitFor(WebElementFacade webElement) { return getRenderedView().waitFor(webElement); }
public Alert getAlert() { return driver.switchTo().alert(); }
public Actions withAction() { WebDriver proxiedDriver = (getDriver() instanceof WebElementFacade) ? ((WebDriverFacade) getDriver()).getProxiedDriver() : getDriver(); return new Actions(proxiedDriver); }
public class FieldEntry {
private final String value;
public FieldEntry(final String value) {
this.value = value;
}
public void into(final WebElement field) {
element(field).type(value);
}
public void into(final net.serenitybdd.core.pages.WebElementFacade field) {
field.type(value);
}
public void intoField(final By bySelector) {
WebElement field = getDriver().findElement(bySelector);
into(field);
}
}
private void notifyScreenChange() { StepEventBus.getEventBus().notifyScreenChange(); }
protected ThucydidesFluentAdapter fluent() { return new ThucydidesFluentAdapter(getDriver()); }
public
public
public void waitForAngularRequestsToFinish() { JavascriptCompatibleVersion.of(getDriver()).ifPresent( driver -> new NgWebDriver(driver).waitForAngularRequestsToFinish() ); }
Inflector inflection = Inflector.getInstance();
@Override public String toString() { return inflection.of(getClass().getSimpleName()) .inHumanReadableForm().toString(); } }
"The page object class com.Nothing.weeklyCashBalancing.pageobjects.Homepage looks dodgy" - I need to see the com.Nothing.weeklyCashBalancing.pageobjects.Homepage
class.
package com.johnlewis.weeklyCashBalancing.pageobjects;
import net.serenitybdd.core.annotations.findby.FindBy; import net.serenitybdd.core.pages.WebElementFacade; import net.thucydides.core.annotations.WhenPageOpens; import net.thucydides.core.pages.PageObject; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver;
public class Homepage extends PageObject {
@WhenPageOpens
public void BrowserMaximize(){
getDriver().manage().window().maximize();
}
@FindBy(id = "j_username")
WebElementFacade userId;
@FindBy(id = "j_password")
WebElementFacade password;
@FindBy(id = "submitButton")
WebElementFacade signInBtn;
@FindBy(id = "branchNumber")
WebElementFacade branchName;
@FindBy(id = "submit")
WebElementFacade submitButton;
@FindBy(id="headerSystemTitle")
WebElementFacade titleOfPage;
public void signInToMyAccount(String uId, String password) {
userId.waitUntilVisible().sendKeys(uId);
this.password.waitUntilVisible().sendKeys(password);
signInBtn.waitUntilVisible().click();
}
public void selectBranch(String brName){
branchName.selectByVisibleText(brName);
submitButton.waitUntilVisible().click();
}
public String verifyTitle(String pageTitle) {
if (titleOfPage.getText().equalsIgnoreCase(pageTitle))
return "User on \""+titleOfPage.getText()+"\" Screen";
else
return "Enter the correct details";
}
}
package net.thucydides.core.pages;
import net.serenitybdd.core.environment.ConfiguredEnvironment; import net.serenitybdd.core.pages.PageObject; import net.serenitybdd.core.pages.PageObjects; import net.thucydides.core.annotations.Fields; import net.thucydides.core.steps.EnclosingClass; import net.thucydides.core.webdriver.Configuration; import net.thucydides.core.webdriver.WebDriverFacade; import net.thucydides.core.webdriver.WebdriverProxyFactory; import org.apache.commons.lang3.StringUtils; import org.openqa.selenium.WebDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.Arrays;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
/**
@author johnsmart */ public class Pages implements Serializable {
private static final long serialVersionUID = 1L;
private transient WebDriver driver;
private static final Logger LOGGER = LoggerFactory.getLogger(Pages.class);
private String defaultBaseUrl;
private final Configuration configuration;
private WebdriverProxyFactory proxyFactory;
private transient boolean usePreviousPage = false;
public Pages(Configuration configuration) { this.configuration = configuration; proxyFactory = WebdriverProxyFactory.getFactory(); }
public Pages() { this(ConfiguredEnvironment.getConfiguration()); }
public Pages(final WebDriver driver) { this(ConfiguredEnvironment.getConfiguration()); this.driver = driver; }
public Pages(final WebDriver driver, Configuration configuration) { this(configuration); this.driver = driver; }
public void setDriver(final WebDriver driver) { this.driver = driver; }
public WebDriver getDriver() { return driver; }
protected WebdriverProxyFactory getProxyFactory() { return proxyFactory; }
public Configuration getConfiguration() { return configuration; }
PageObject currentPage = null;
public
public
@SuppressWarnings("unchecked")
public
@SuppressWarnings("unchecked")
public
private
private void openHeadlessDriverIfNotOpen() { if (browserIsHeadless()) { driver.get("about:blank"); } }
private boolean browserNotOpen() { if (getDriver() instanceof WebDriverFacade) { return !((WebDriverFacade) getDriver()).isInstantiated(); } else { return StringUtils.isEmpty(getDriver().getCurrentUrl()); } }
private boolean browserIsHeadless() {
if (getDriver() instanceof WebDriverFacade) {
return (((WebDriverFacade) getDriver()).getProxiedDriver() instanceof HtmlUnitDriver);
} else {
return (getDriver() instanceof HtmlUnitDriver);
}
}
private
private
private void cacheCurrentPage(PageObject newPage) { this.currentPage = newPage; }
private
public boolean isCurrentPageAt(final Class<? extends PageObject> pageObjectClass) { try { PageObject pageCandidate = getCurrentPageOfType(pageObjectClass); String currentUrl = getDriver().getCurrentUrl(); return pageCandidate.compatibleWithUrl(currentUrl); } catch (WrongPageError e) { return false; } }
/**
@throws IllegalArgumentException
*/
@SuppressWarnings("unchecked")
private
} catch (NoSuchMethodException e) { LOGGER.warn("This page object does not appear have a constructor that takes a WebDriver parameter: {} ({})", pageObjectClass, e.getMessage()); thisPageObjectLooksDodgy(pageObjectClass, "This page object does not appear have a constructor that takes a WebDriver parameter"); } catch (InvocationTargetException e) { // Unwrap the underlying exception LOGGER.warn("Failed to instantiate page of type {} ({})", pageObjectClass, e.getTargetException()); thisPageObjectLooksDodgy(pageObjectClass,"Failed to instantiate page (" + e.getTargetException() +")"); }catch (Exception e) { //shouldn't even get here LOGGER.warn("Failed to instantiate page of type {} ({})", pageObjectClass, e); thisPageObjectLooksDodgy(pageObjectClass,"Failed to instantiate page (" + e +")"); } return currentPage; }
private
} catch (NoSuchMethodException e) {
// Try a different constructor
}
return newPage;
}
private
private
private
private boolean hasPageFactoryProperty(Object pageObject) {
java.util.Optional
private void setPageFactory(Object pageObject) throws IllegalAccessException { Fields.of(pageObject.getClass()).withName("pages").ifPresent( field -> assignTo(field, pageObject) ); }
private void assignTo(Field pagesField, Object pageObject) { try { pagesField.setAccessible(true); pagesField.set(pageObject, this); } catch (IllegalAccessException e) { LOGGER.warn("Failed to assign page object field: ", e); } }
private void thisPageObjectLooksDodgy(final Class<? extends PageObject> pageObjectClass, String message) {
String errorDetails = "The page object " + pageObjectClass + " looks dodgy:\n" + message;
throw new WrongPageError(errorDetails);
}
private void thisIsNotThePageYourLookingFor(final Class<? extends PageObject> pageObjectClass) {
String errorDetails = "This is not the page you're looking for: "
+ "I was looking for a page compatible with " + pageObjectClass + " but "
+ "I was at the URL " + getDriver().getCurrentUrl();
throw new WrongPageError(errorDetails);
}
/**
The default URL for this set of tests, or the system default URL if undefined. */ public String getDefaultBaseUrl() {
String baseUrl = defaultBaseUrl; if (isNotEmpty(getConfiguration().getBaseUrl())) { baseUrl = getConfiguration().getBaseUrl(); } return baseUrl; }
/**
public Pages onSamePage() { usePreviousPage = true; return this; }
public static
package com.johnlewis.weeklyCashBalancing.pageobjects;
import net.serenitybdd.core.annotations.findby.FindBy; import net.serenitybdd.core.pages.WebElementFacade; import net.thucydides.core.annotations.WhenPageOpens; import net.thucydides.core.pages.PageObject; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver;
public class Homepage extends PageObject {
@WhenPageOpens
public void BrowserMaximize(){
getDriver().manage().window().maximize();
}
@FindBy(id = "j_username")
WebElementFacade userId;
@FindBy(id = "j_password")
WebElementFacade password;
@FindBy(id = "submitButton")
WebElementFacade signInBtn;
@FindBy(id = "branchNumber")
WebElementFacade branchName;
@FindBy(id = "submit")
WebElementFacade submitButton;
@FindBy(id="headerSystemTitle")
WebElementFacade titleOfPage;
public void signInToMyAccount(String uId, String password) {
userId.waitUntilVisible().sendKeys(uId);
this.password.waitUntilVisible().sendKeys(password);
signInBtn.waitUntilVisible().click();
}
public void selectBranch(String brName){
branchName.selectByVisibleText(brName);
submitButton.waitUntilVisible().click();
}
public String verifyTitle(String pageTitle) {
if (titleOfPage.getText().equalsIgnoreCase(pageTitle))
return "User on \""+titleOfPage.getText()+"\" Screen";
else
return "Enter the correct details";
}
}
I don't think it is the page object - the best thing would be to place a breakpoint in the code (Pages.java:223) to see exactly why it is failing.
its send the error message of failing.its a catch block
You will need to look at the exception and find the root cause exception. It might appear in the logs when the test fails.
its going to line no 290 & showing @message. private void thisPageObjectLooksDodgy(final Class<? extends PageObject> pageObjectClass, String message) {
String errorDetails = "The page object " + pageObjectClass + " looks dodgy:\n" + message;
throw new WrongPageError(errorDetails);
}
I would need to walk through the code in a remote session to trouble-shoot this. Does your company have a commercial support contract for Serenity?
no
If your company is using Serenity in a commercial context, it would be worthwhile for them to look at the support options (https://johnfergusonsmart.com/serenity-bdd-mentoring/). It is much easier than via email exchanges.
package net.thucydides.core.annotations.locators;
import net.serenitybdd.core.environment.ConfiguredEnvironment; import net.serenitybdd.core.pages.PageObject; import net.thucydides.core.webdriver.Configuration; import net.thucydides.core.webdriver.ElementLocatorFactorySelector; import net.thucydides.core.webdriver.ElementProxyCreator; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;
public class SmartElementProxyCreator implements ElementProxyCreator {
@Override
public void proxyElements(PageObject pageObject, WebDriver driver) {
PageFactory.initElements(new SmartFieldDecorator(locatorFactories().getLocatorFor(driver), driver, pageObject), pageObject);
}
@Override
public void proxyElements(PageObject pageObject, WebDriver driver, int timeoutInSeconds) {
ElementLocatorFactory finder = locatorFactories().withTimeout(timeoutInSeconds).getLocatorFor(driver);
PageFactory.initElements(new SmartFieldDecorator(finder, driver, pageObject), pageObject);
}
private ElementLocatorFactorySelector locatorFactories() {
Configuration configuration = ConfiguredEnvironment.getConfiguration();
return new ElementLocatorFactorySelector(configuration);
}
}
I'm fairly familiar with the Serenity code - I'm more interested in the contents of the exceptions, not which Serenity methods throw them.
There are a lot of things to go through in that code base. Since it is project-specific support and not a Serenity defect, it could only be looked at as part of a support contract.
Hi John, after all debug in the error here the code which getting the error,
try {
return (DriverSource) Class.forName(providedImplementation).newInstance();
} catch (Exception e) {
throw new RuntimeException("Could not instantiate the custom webdriver provider of type " + providedImplementation);
}
package net.thucydides.core.webdriver;
import com.google.common.base.Preconditions; import net.thucydides.core.ThucydidesSystemProperty; import net.thucydides.core.util.EnvironmentVariables;
import static net.thucydides.core.webdriver.WebDriverFactory.getDriverFrom;
/**
Time: 12:39 PM */ public class ProvidedDriverConfiguration {
private final EnvironmentVariables environmentVariables;
public ProvidedDriverConfiguration(EnvironmentVariables environmentVariables) { this.environmentVariables = environmentVariables; }
public boolean isProvided() { return getDriverFrom(environmentVariables).equals("provided"); }
**public DriverSource getDriverSource() { String providedDriverType = getDriverName(); Preconditions.checkNotNull(providedDriverType, "No provider type was specified in 'webdriver.provided.type'");
String providedImplementation = environmentVariables.getProperty("webdriver.provided." + providedDriverType);
Preconditions.checkNotNull(providedImplementation,
"No provider implementation was specified in 'webdriver.provided.'" + providedDriverType);
try {
return (DriverSource) Class.forName(providedImplementation).newInstance();
} catch (Exception e) {
throw new RuntimeException("Could not instantiate the custom webdriver provider of type " + providedImplementation);
}
}**
public String getDriverName() { return environmentVariables.getProperty(ThucydidesSystemProperty.WEBDRIVER_PROVIDED_TYPE); } }
String providedDriverType = getDriverName(); its getting as "mydriver"
You don't need to use a provided driver for your code.
what should i use in that place
Testing started at 17:23 ... 17:23:50: Executing tasks ':cleanTest :test --tests "com.Nothing.weeklyCashBalancing.runners.CucumberTest"'...
:cleanTest UP-TO-DATE :compileJava NO-SOURCE :processResources NO-SOURCE :classes UP-TO-DATE :compileTestJava :processTestResources UP-TO-DATE :testClasses :test SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. Feature: Login into Weekly Cash Balancing Application
Scenario Outline: To verify that user is able to login into weekly cash balancing application # src/test/resources/features/LoginWCB.feature:5 Given User opens the WCB Application url to login Then verify the title of page is "