How To Highlight Locators In WebDriver Test Cases
It's likely that you'll run into odd test behavior that makes you question the locators you're using in a test. But how do you interrogate your locators to make sure they are doing what you expect?
By leveraging some simple JavaScript and CSS styling, you can highlight a targeted element on the page so you can visually inspect it to make sure it's the one you want.import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement ; import org.openqa.selenium.firefox. FirefoxDriver; public class HighlightElement { WebDriver driver; JavascriptExecutor js; @Before public void setUp() throws Exception { driver = new FirefoxDriver(); js = (JavascriptExecutor) driver; } @After public void tearDown() throws Exception { driver.quit(); }
// filename: HighlightElement.java private void highlightElement(WebElement element, int duration) throws InterruptedException { String original_style = element.getAttribute("style"); js.executeScript( "arguments[0].setAttribute(arguments[1], arguments[2])", element, "style", "border: 2px solid red; border-style: dashed;"); if (duration > 0) { Thread.sleep(duration * 1000); js.executeScript( "arguments[0].setAttribute( arguments[1], arguments[2])", element, "style", original_style); } } @Test public void highlightElementTest() throws InterruptedException { driver.get("http://the-internet.herokuapp.com/large") ; WebElement element = driver.findElement(By.id(" sibling-2.3")); highlightElement(element, 3); } }
Comments
Post a Comment