0% found this document useful (0 votes)
3 views24 pages

Selenium Syntax

Uploaded by

rakeshdkaatkar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views24 pages

Selenium Syntax

Uploaded by

rakeshdkaatkar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

WebDriver Setup

import [Link];

import [Link];

WebDriver driver = new ChromeDriver();

[Link]().window().maximize();

[Link]("[Link]

[Link]();

WebElement Locators

[Link]([Link]("username"));

[Link]([Link]("password"));

[Link]([Link]("input-box"));

[Link]([Link]("button"));

[Link]([Link]("Login"));

[Link]([Link]("Log"));

[Link]([Link]("input[type='text']"));

[Link]([Link]("//input[@id='username']"));

WebElement Common Methods

WebElement element = [Link]([Link]("username"));

[Link]();

[Link]("Ranju Chinni");

[Link]();

String text = [Link]();

String value = [Link]("value");


boolean isDisplayed = [Link]();

boolean isEnabled = [Link]();

boolean isSelected = [Link]();

Actions Class (Mouse & Keyboard Events)

import [Link];

Actions action = new Actions(driver);

[Link](element).perform();

[Link](element).perform();

[Link](element).perform(); // Right click

[Link](element).perform(); // Hover

[Link](source, target).perform();

[Link]([Link]).click(element).keyUp([Link]).perform();

Keyboard Methods

sendKeys()

→ Sends a sequence of keystrokes to the active element.

Syntax:

Actions action = new Actions(driver);

[Link]([Link]).perform();

Example:

WebElement inputBox = [Link]([Link]("username"));

Actions action = new Actions(driver);

[Link](inputBox).sendKeys("Ranju Chinni").perform();
keyDown()

→ Presses (holds down) a modifier key (like SHIFT, CTRL, or ALT) without releasing it.

Syntax:

[Link]([Link]).sendKeys("hello").keyUp([Link]).perform();

Example:

Actions action = new Actions(driver);

[Link]([Link])

.sendKeys("selenium")

.keyUp([Link])

.perform(); // outputs SELENIUM

keyUp()

→ Releases a key that was pressed using keyDown().

Syntax:

[Link]([Link]).sendKeys("a").keyUp([Link]).perform();

Example (Select All):

Actions action = new Actions(driver);

[Link]([Link])

.sendKeys("a")

.keyUp([Link])

.perform();

sendKeys(WebElement target, CharSequence keys)

→ Sends keystrokes to a specific element.

Syntax:

[Link](element, "Automation").perform();
Example:

WebElement input = [Link]([Link]("search"));

Actions action = new Actions(driver);

[Link](input, "Java Testing").perform();

copy-paste Example (CTRL + C / CTRL + V)

→ Demonstrates keyboard shortcuts.

Example:

WebElement input1 = [Link]([Link]("source"));

WebElement input2 = [Link]([Link]("target"));

Actions action = new Actions(driver);

[Link]("Selenium Rocks!");

[Link]([Link]).sendKeys("a").sendKeys("c").keyUp([Link]).perf
orm();

[Link]();

[Link]([Link]).sendKeys("v").keyUp([Link]).perform();

Press ENTER or TAB

Example:

Actions action = new Actions(driver);

[Link]([Link]).perform(); // Move to next field

[Link]([Link]).perform(); // Press Enter

Press ESCAPE

Example:
Actions action = new Actions(driver);

[Link]([Link]).perform(); // Close modal, dialog, etc.

Combination Example (Shift + Tab navigation)

Actions action = new Actions(driver);

[Link]([Link])

.sendKeys([Link])

.keyUp([Link])

.perform();

Example: Enter data and submit form

WebElement searchBox = [Link]([Link]("q"));

Actions action = new Actions(driver);

[Link](searchBox, "Selenium Interview Questions")

.sendKeys([Link])

.perform();

Example: Simulate Keyboard Shortcuts

Shortcu
Code Example
t

Ctrl + A
[Link]([Link]).sendKeys("a").keyUp([Link]).perform
(Select
();
All)

Ctrl + C [Link]([Link]).sendKeys("c").keyUp([Link]).perform
(Copy) ();

Ctrl + V [Link]([Link]).sendKeys("v").keyUp([Link]).perform
(Paste) ();
Shortcu
Code Example
t

Ctrl + X [Link]([Link]).sendKeys("x").keyUp([Link]).perform
(Cut) ();

Alt + Tab
(Switch
Not supported directly in Selenium — OS-level shortcut
Window
)

JavaScriptExecutor

import [Link];

JavascriptExecutor js = (JavascriptExecutor) driver;

// Scroll

[Link]("[Link](0, 500)");

[Link]("arguments[0].scrollIntoView(true);", element);

// Click

[Link]("arguments[0].click();", element);

// Set value

[Link]("arguments[0].value='test';", element);

// Get title

String title = (String) [Link]("return [Link]");


Waits

Implicit Wait

[Link]().timeouts().implicitlyWait([Link](10));

Explicit Wait

WebDriverWait wait = new WebDriverWait(driver, [Link](15));

WebElement element =
[Link]([Link]([Link]("login")));

Fluent Wait

Wait<WebDriver> fluentWait = new FluentWait<>(driver)

.withTimeout([Link](20))

.pollingEvery([Link](2))

.ignoring([Link]);

WebElement element = [Link](driver -> [Link]([Link]("username")));

TestNG Annotations

import [Link].*;

public class ExampleTest {

@BeforeSuite

public void beforeSuite() {}

@BeforeClass

public void beforeClass() {}


@BeforeMethod

public void beforeMethod() {}

@Test(priority = 1, groups = "smoke")

public void testLogin() {}

priority

Purpose: Defines the order in which tests run.


Lower number = higher priority.

Syntax:

@Test(priority = 1)

public void loginTest() { }

@Test(priority = 2)

public void searchProductTest() { }

enabled

Purpose: Enable or disable a test method.


Default: true

Syntax:

@Test(enabled = false)

public void skipThisTest() { }

dependsOnMethods

Purpose: Makes a test run after the specified method(s) have passed.

Syntax:

@Test
public void loginTest() { }

@Test(dependsOnMethods = {"loginTest"})

public void dashboardTest() { }

dependsOnGroups

Purpose: Makes a test depend on an entire group of tests.

Syntax:

@Test(groups = "smoke")

public void loginTest() { }

@Test(dependsOnGroups = {"smoke"})

public void verifyAfterSmokeTests() { }

alwaysRun

Purpose: Forces a test to run even if the dependent test fails.

Syntax:

@Test(dependsOnMethods = {"loginTest"}, alwaysRun = true)

public void logoutTest() { }

timeOut

Purpose: Sets maximum time (in milliseconds) a test can take before being marked as
failed.

Syntax:

@Test(timeOut = 3000)

public void pageLoadTest() throws InterruptedException {


[Link](2000);

invocationCount

Purpose: Runs the same test multiple times automatically.

Syntax:

@Test(invocationCount = 3)

public void retryLoginTest() {

[Link]("Login attempt");

invocationTimeOut

Purpose: Sets a total time limit for all invocations of a test method.

Syntax:

@Test(invocationCount = 5, invocationTimeOut = 10000)

public void performanceTest() { }

expectedExceptions

Purpose: Marks the test as passed if a specific exception is thrown.

Syntax:

@Test(expectedExceptions = [Link])

public void divideByZeroTest() {

int x = 1 / 0;

expectedExceptionsMessageRegExp
Purpose: Passes the test only if both the exception type and message match.

Syntax:

@Test(

expectedExceptions = [Link],

expectedExceptionsMessageRegExp = "For input string: .*"

public void invalidNumberTest() {

[Link]("abc");

groups

Purpose: Categorizes tests into logical groups (smoke, regression, sanity, etc.).

Syntax:

@Test(groups = {"regression"})

public void searchTest() { }

@Test(groups = {"smoke"})

public void loginTest() { }

dataProvider

Purpose: Links a test to a @DataProvider method for data-driven testing.

Syntax:

@DataProvider(name = "loginData")

public Object[][] getData() {

return new Object[][] { {"user1", "pass1"}, {"user2", "pass2"} };

}
@Test(dataProvider = "loginData")

public void loginTest(String username, String password) {

[Link](username + " : " + password);

dataProviderClass

Purpose: Specifies the class where the DataProvider is defined (useful if provider is in
another class).

Syntax:

@Test(dataProvider = "getData", dataProviderClass = [Link])

public void testData(String name, int age) { }

description

Purpose: Adds a short description for documentation and reports.

Syntax:

@Test(description = "Verify login functionality for valid credentials")

public void loginTest() { }

threadPoolSize

Purpose: Runs the test in parallel using multiple threads.

Syntax:

@Test(invocationCount = 6, threadPoolSize = 3)

public void parallelTest() {

[Link]("Thread ID: " + [Link]().getId());

}
retryAnalyzer

Purpose: Re-runs a failed test automatically (commonly used with Retry logic).

Syntax:

@Test(retryAnalyzer = [Link])

public void unstableTest() {

[Link](false);

Example Retry Class:

public class RetryAnalyzer implements IRetryAnalyzer {

private int count = 0;

public boolean retry(ITestResult result) {

if (count < 2) {

count++;

return true;

return false;

singleThreaded

Purpose: Ensures that all test methods in the same class run in a single thread.

Syntax:

@Test(singleThreaded = true)

public class ThreadSafeTests { }


Summary Table

Parameter Description Example

Defines
priority execution @Test(priority=1)
order

Enables/disa
enabled @Test(enabled=false)
bles test

Runs after
dependsOnMethods @Test(dependsOnMethods="login")
another test

Runs after
dependsOnGroups @Test(dependsOnGroups="smoke")
group of tests

Forces
alwaysRun @Test(alwaysRun=true)
execution

Sets max
timeOut @Test(timeOut=2000)
time

invocationCount Repeats test @Test(invocationCount=5)

Timeout for @Test(invocationCount=5,


invocationTimeOut
all runs invocationTimeOut=10000)

Expected @Test(expectedExceptions=NullPointerExce
expectedExceptions
exception [Link])

Match
expectedExceptionsMessage @Test(expectedExceptionsMessageRegExp=
exception
RegExp ".*error.*")
message

groups Group tests @Test(groups="smoke")

Data-driven
dataProvider @Test(dataProvider="data")
test

Data from
dataProviderClass @Test(dataProviderClass=[Link])
another class
Parameter Description Example

description Add notes @Test(description="Login check")

Parallel
threadPoolSize @Test(threadPoolSize=3)
execution

Retry failed
retryAnalyzer @Test(retryAnalyzer=[Link])
test

Force single-
singleThreaded @Test(singleThreaded=true)
thread

@AfterMethod

public void afterMethod() {}

@AfterClass

public void afterClass() {}

@AfterSuite

public void afterSuite() {}

Assertions

import [Link];

[Link](actual, expected);

[Link](condition);

[Link](condition);

[Link](object);
[Link]("Forcefully fail this test");

Handling Windows / Tabs

String mainWindow = [Link]();

Set<String> allWindows = [Link]();

for (String window : allWindows) {

if (![Link](mainWindow)) {

[Link]().window(window);

[Link]();

[Link]().window(mainWindow);

Handling Frames

[Link]().frame("frameName");

[Link]().frame(0);

[Link]().frame([Link]([Link]("frameId")));

[Link]().defaultContent();

[Link]().parentFrame();

Handling Alerts

Alert alert = [Link]().alert();

[Link]([Link]());

[Link](); // OK

[Link](); // Cancel
[Link]("text");

Dropdown (Select Class)

import [Link];

Select select = new Select([Link]([Link]("dropdown")));

[Link]("Option 1");

[Link](2);

[Link]("opt2");

[Link]();

List<WebElement> options = [Link]();

Screenshot

File src = ((TakesScreenshot)driver).getScreenshotAs([Link]);

[Link](src, new File("[Link]"));

Page Object Model Example

public class LoginPage {

WebDriver driver;

@FindBy(id="username") WebElement username;

@FindBy(id="password") WebElement password;

@FindBy(id="loginBtn") WebElement loginBtn;

public LoginPage(WebDriver driver) {

[Link] = driver;
[Link](driver, this);

public void login(String user, String pass) {

[Link](user);

[Link](pass);

[Link]();

File Upload / Download

// File Upload

[Link]([Link]("fileUpload")).sendKeys("C:\\path\\[Link]");

// File Download (auto config)

HashMap<String, Object> prefs = new HashMap<>();

[Link]("download.default_directory", "C:\\downloads");

ChromeOptions options = new ChromeOptions();

[Link]("prefs", prefs);

WebDriver driver = new ChromeDriver(options);

Headless Browser

ChromeOptions options = new ChromeOptions();

[Link]("--headless");

WebDriver driver = new ChromeDriver(options);


Logs

LogEntries logs = [Link]().logs().get("browser");

for (LogEntry entry : logs) {

[Link]([Link]());

Actions Class — Full Syntax & Methods

import [Link];

// Create Actions object

Actions action = new Actions(driver);

// Basic Actions

[Link](element).perform();

[Link](element).perform();

[Link](element).perform(); // Right-click

[Link](element).perform(); // Mouse hover

[Link](element).perform();

[Link](element).perform();

// Drag and Drop

[Link](source, target).perform();

[Link](source, 100, 0).perform();

// Keyboard Actions
[Link]([Link]).perform();

[Link]([Link]).sendKeys("a").keyUp([Link]).perform();

// Composite Actions

[Link](element1)

.click()

.moveToElement(element2)

.click()

.build()

.perform();

JavaScriptExecutor — Complete Syntax

import [Link];

// Initialize

JavascriptExecutor js = (JavascriptExecutor) driver;

// Scroll Operations

[Link]("[Link](0,500)");

[Link]("arguments[0].scrollIntoView(true);", element);

[Link]("[Link](0, [Link])");

// Click Element

[Link]("arguments[0].click();", element);

// Set / Get Values


[Link]("arguments[0].value='Ranju Chinni';", element);

String text = (String) [Link]("return arguments[0].value;", element);

// Highlight Element

[Link]("arguments[0].[Link]='3px solid red'", element);

// Disable Element

[Link]("arguments[0].setAttribute('disabled','true')", element);

// Get Page Details

String title = (String) [Link]("return [Link]");

String url = (String) [Link]("return [Link]");

// Refresh Page

[Link]("[Link](0)");

Extent Reports (Advanced Logging & Reporting)

Maven Dependency

<dependency>

<groupId>[Link]</groupId>

<artifactId>extentreports</artifactId>

<version>5.1.0</version>

</dependency>

Setup in Code

import [Link].*;

import [Link];
ExtentSparkReporter spark = new ExtentSparkReporter("[Link]");

ExtentReports extent = new ExtentReports();

[Link](spark);

ExtentTest test = [Link]("Login Test").assignAuthor("Ranju


Chinni").assignCategory("Regression");

Logging

[Link]([Link], "Browser launched");

[Link]("Login successful");

[Link]("Element not found");

[Link]("Feature not implemented");

Add Screenshot

[Link]("screenshots/[Link]");

Flush Report

[Link]();

XPath Axes — Complete Syntax with Examples

Axis Description Example

Selects all ancestors of the


ancestor //input[@id='username']/ancestor::form
current node

ancestor-or- Ancestor nodes + current


//div[@id='main']/ancestor-or-self::*
self node

child Selects all direct children //ul[@id='menu']/child::li

Selects all descendants


descendant //div[@id='container']/descendant::a
(children, grandchildren)
Axis Description Example

descendant-
Descendants + current node //div[@id='container']/descendant-or-self::*
or-self

All nodes after the current


following //h2/following::p
node in the document

following- All siblings after the current //label[@for='email']/following-


sibling node sibling::input

All nodes before the current


preceding //input[@id='password']/preceding::label
node in the document

preceding- All siblings before the current //input[@id='password']/preceding-


sibling node sibling::label

parent Parent of the current node //input[@id='email']/parent::div

self Current node itself //div[@class='header']/self::div

Advanced XPath Examples

//div[@class='container']//child::span[text()='Click Me']

//input[@id='email']/following::button[1]

//ul/li[normalize-space(text())='Home']/preceding-sibling::li

//div[@id='main']//descendant::input[@type='text']

//table[@id='data']//tr[td[text()='Ranju Chinni']]/following-sibling::tr[1]

Bonus – Useful Snippets

Take Screenshot (Attach to Extent Report)

File src = ((TakesScreenshot) driver).getScreenshotAs([Link]);

String path = "screenshots/[Link]";

[Link](src, new File(path));

[Link](path);
Highlight Element Before Clicking

public void highlightElement(WebDriver driver, WebElement element) {

JavascriptExecutor js = (JavascriptExecutor) driver;

[Link]("arguments[0].[Link]='3px solid red'", element);

Retry Logic

@Test(retryAnalyzer = [Link])

public void testRetry() {

[Link](false);

You might also like