2

When interacting with different elements and applying multiple actions it may be quite convenient in some situations if we could do:

WebElement myInput = driver.findElement(By.id("my-input-id"));
myInput.clear().sendKeys("test");

Instead of:

WebElement myInput = driver.findElement(By.id("my-input-id"));
myInput.clear()
myInput.sendKeys("test");

But, the problem is clear(), sendKeys() and other "action" methods cannot be chained as is - they return void and not the current WebElement.

What would be the easiest way to achieve chaining multiple actions?

3

The only solution I can see in Java is similar to what FDM suggested: using Adapter design pattern that wraps original WebElement.

public class MyWebElement {

  private final WebElement original;

  public MyWebElement(WebElement original) { this.original = original; }

  private MyWebElement click() {
     original.click();
     return this;
  }
  ...
}

Similarly, with WebDriver.

However, I wonder what would be ROI from chaining WebElements in general.

Usually, in test automation you use fluent interfaces to have concise and more readable tests. In tests you use Page Objects, Scenarios, Actions, etc, while WebElements are hidden inside of them. It would rather make sense to make Page Objects, Scenarios and Actions chainable.

2

Would your question be for C# than the answer would simply be extension methods.

For JAVA however, I can only think of subclassing Driver and WebElement and add the method signatures you need, if you want to keep the syntax similar to what you posted. Adding your own methods even allows for custom logging and waiting (e.g. my framework method SetText waits for the element to be visible before SendKeys, and then clears it, so I never have to add a wait or a clear() in my PageObjects again).

So basically, if you create a good framework method that combines all (technical) steps to enter text, you will need only one line of code in your PageObjects.

However (and this is my opinion) I prefer the original syntax you posted because it is more readable. Especially if you would start having longer chains.

1

In my opinion, the easiest way is to create your own wrappers, for example:

public WebElement customSendKeys(WebElement we, String textToEnter) {
    we.sendKeys(textToEnter);
    return this;
}

But I would agree with previous answer, if you use page object pattern then you just write it once and don't bother with repeating the same code again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.