Highlight Web Elements on the page in Selenium tests?
Overview
Let’s see how to highlight web elements using the Selenium tool. We can use the Event listener to highlight web elements on the web page under test. To accomplish the task, we can use JavascriptExecutor and EventFiringWebDriver. Find the code below that draws a visible border to highlight web element interactions during selenium tests.
Basic Things
WebDriverEventListener is an interface with method signatures for the set of actions performed each time the event occurs.
AbstractWebDriverEventListener is an abstract base class, you can use this base class if you want to implement a WebDriverEventListener. Methods provided by this class have empty implementations.
WebElementHighlighter is the class only interested in the beforeFindBy() method.
Highlight Web Elements Code
public class WebElementHighlighter extends AbstractWebDriverEventListener { public void beforeFindBy(By by, WebElement element, WebDriver driver){ WebElement webelement = driver.findElement(by); if (driver instanceof JavascriptExecutor) { ((JavascriptExecutor)driver).executeScript("arguments[0].style.border='10px solid green'", webelement); } File scrFile = ((TakesScreenshot) driver) .getScreenshotAs(OutputType.FILE); try { FileUtils.copyFile(scrFile, new File("images/HighlighterScreenCapture" + currentTime() + ".jpg")); } catch (IOException e) { e.printStackTrace(); } } public String currentTime() { Date todayDate = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("ddMMyy_HHmmss"); String formattDate = formatter.format(todayDate); return formattDate; } }
Sample Selenium Tests
Let’s code a sample search test method to enter some info on the Twitter page..
public class TwitterTest { public WebDriver webDriver = null; public EventFiringWebDriver driver = null; @BeforeClass public void init() { System.setProperty("webdriver.gecko.driver", "drivers/geckodriver.exe"); webDriver = new FirefoxDriver(); driver = new EventFiringWebDriver(webDriver); WebElementHighlighter highlighter = new WebElementHighlighter(); driver.register(highlighter); } // Twitter page test @Test public void SampleTest() throws Throwable { driver.get("https://www.twitter.com/login"); driver.manage().window().maximize(); driver.findElement(By.name("session[username_or_email]")).clear(); driver.findElement(By.name("session[username_or_email]")) .sendKeys("TestingDocs.com"); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(120, 1)); wait.until(ExpectedConditions.titleContains("Twitter")); } @AfterClass public void closeBrowser() { driver.quit(); } }
The output of the Test
Run the TestNG selenium test. The highlighter highlights the web elements during the test interactions.
—
TestNG Tutorials
TestNG Tutorials on this website can be found at:
https://www.testingdocs.com/testng-framework-tutorial/
For more details on the TestNG Framework, visit the official website of TestNG at: