Please excuse terminology issues in this post. This appears to be a basic Java question, I just am not finding results in my searching.
I would like to create a method that could potentially return multiple types in a Selenium pageObject framework. See example below:
public class ProductPage extends BasePage {
public ProductPage(WebDriver driver) {
super(driver);
}
public ProductPage enterValue(String inputText) {
driver.findElement(By.id("someId")).sendKeys(inputText);
return this;
}
The method enterValue occasionally lands to a different page than ProductPage. If I know it could navigate elsewhere, I tend to create a different method. However, this is making the tests harder for others to understand and maintain.
Is there a way to obfuscate the return type and add a conditional inside the method that allows the method to return a different type? Here is my best attempt:
public NotSureWhatToPutHere enterValue(String inputText) {
driver.findElement(By.id("someId")).sendKeys(inputText);
if(isAlertPresent){
return new ProductAlertPage(driver);
} else if (isErrorDisplayed) {
return new ErrorPage(driver);
} else {
return this;
}
}
You need to use polymorphism or inheritance.
so ProductAlertPage
and ErrorPage
both inherit from an interface
or class
like eg Page
. Then you can have a return type of Page
.
In your case ErrorPage
and ProductAlertPage
should also extend BasePage
and then you can return BasePage
as return type.
public BasePage enterValue(String inputText) {
driver.findElement(By.id("someId")).sendKeys(inputText);
if(isAlertPresent){
return new ProductAlertPage(driver);
} else if (isErrorDisplayed) {
return new ErrorPage(driver);
} else {
return this;
}
}
You can try :
public Page enterValue(String inputText) {
}
Where is Page
is extended
by both ProductAlertPage
and ErrorPage
.
public ProductAlertPage extends Page {
// code for ProductAlertPage
}
public ErrorPage extends Page {
// code for ErrorPage
}
Alternatively, you can also make Page
an interface
and have both ProductAlertPage
and ErrorPage
implements the interface
as shown below:
public ProductAlertPage implements Page {
// code for ProductAlertPage
}
public ErrorPage implements Page {
// code for ErrorPage
}
This is a better solution as it is less tightly coupled.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.