You are on page 1of 15

1.

String Methods
String length() ->>> length of the string
String charAt()->>> returns a char value at the given index number
String concat()->>> combines specified string at the end of this string
String contains()->>> returns true if chars are found in the string
String startsWith()->>> checks if this string starts with given prefix
String endsWith()->>> checks if this string ends with given suffix
String equals()->>> compares the contents of two given strings
String indexOf()->>> returns index of given character value or substring
String isEmpty()->>> checks if this string is empty
String replace()->>> returns a string replacing all the old char to new char
String substring()->>> returns a part of the string
String toCharArray()->>> converts this string into character array
String toLowerCase()->>> returns the string in lowercase letter
String toUpperCase()->>> returns the string in uppercase letter
String trim()->>> eliminates leading and trailing spaces

2. CSS Selectors Cheat Sheet

Every element does not have an id -> static id, unique name, unique link text. For those
elements we need to build xpath to find and then perform actions on them.

Whatever we use to find an element, id, name, xpath, css -> It should always be unique. It
should only find one matching node unless we want to capture a list of elements

Syntax:
tag[attribute='value']
“#” -> Id
“.” -> Class

Element Displayed Example Text Box:


input[id=displayed-text]
#displayed-text input
#displayed-text
input[class=displayed-class]
.displayed-class
input.displayed-class

Appending Classes
.class1.class2.class3 -> Until we find a unique element

Using wildcards in CSS Selectors:


“^” -> Represents the starting text
“$” -> Represents the ending text
“*” -> Represents the text contained
Syntax: tag[attribute=’value’]
Examples:
input[class='inputs'] -> Only 1 matching node
input[class^='inputs'] -> Two matching nodes
input[class='displayed-class'] - No matching nodes
input[class$='class'] -> One matching node
input[class*='displayed-class'] -> One matching node

Finding Children
fieldset -> 10 matching nodes
Fieldset>table
fieldset>#product -> One matching node
fieldset>button -> One matching node
Fieldset>a fieldset>input#name

3. XPATH Cheat Sheet


Every element does not have an id -> static id, unique name, unique link text. For those
elements we need to build xpath to find and then perform actions on them.

Whatever we use to find an element, id, name, xpath -> It should always be unique. It
should only find one matching node unless we want to capture a list of elements.

Difference between single ‘/’ or double ‘//’

Single slash ‘/’ anywhere in xpath signifies to look for the element immediately inside the
parent element.
Double slash ‘//’ signifies to look for any child or nested child element inside the parent
element.

Syntax: //tag[@attribute='value']

Relative xpath using single ‘/’ for Login link


//div[@id='navbar']/div/div/div/ul/li[2]/a

Relative xpath using double ‘//’ for Login link.


//div[@id='navbar']//ul/li[2]/a Don’t use

“*”, always use the tag name.

Using Text of the element to build xpath Finding Login link:


//div[@class='homepage-hero']//a[text()='Enroll now']
Using Contains to find the elements:
Syntax: //tag[contains(attribute, ‘value’)]

Finding Login link:


//div[@id='navbar']//a[contains(text(),'Login')]
//div[@id='navbar']//a[contains(@class,'navbar-link') and contains(@href,'sign_in')]

Using Starts-With to find the elements:


Syntax: //tag[starts-with(attribute, ‘value’)]

Finding Login link:


//div[@id='navbar']//a[starts-with(@class,'navbar-link')]

Parent
Syntax: xpath-to-some-element//parent

Preceding Sibling
Syntax: xpath-to-some-element//preceding-sibling

Following Sibling
Syntax: xpath-to-some-element//following-sibling

4. Navigate between pages


driver.navigate().to(link);
driver.navigate().back();
driver.navigate().forward();
driver.navigate().refresh();

5. State of the element


Link.isEnabled()

6. Working with list of radio button

public void testListOfElements() throws Exception {

boolean isChecked = false;

List<WebElement> radioButtons = driver.findElements(


By.xpath("//input[contains(@type,'radio') and
contains(@name,'cars')]"));
int size = radioButtons.size();
System.out.println("Size of the list: " + size);
for (int i=0; i<size; i++) {
isChecked = radioButtons.get(i).isSelected();

if (!isChecked) {
radioButtons.get(i).click();
Thread.sleep(2000);
}}}
7. Working with drop down
public void testDropdown() throws Exception {
driver.get(baseUrl);
WebElement element = driver.findElement(By.id("carselect"));
Select sel = new Select(element);

Thread.sleep(2000);
System.out.println("Select Benz by value");
sel.selectByValue("benz");

Thread.sleep(2000);
System.out.println("Select Honda by index");
sel.selectByIndex(2);

Thread.sleep(2000);
System.out.println("Select BMW by visible text");
sel.selectByVisibleText("BMW");

Thread.sleep(2000);
System.out.println("Print the list of all options");
List<WebElement> options = sel.getOptions();
int size = options.size();

for (int i=0; i<size; i++) {


String optionName = options.get(i).getText();
System.out.println(optionName);
}
}
8. Multiple select option in dropdown

public void testMultiSelect() throws Exception {

driver.get(baseUrl);

WebElement element = driver.findElement(By.id("multiple-select-


example"));
Select sel = new Select(element);

Thread.sleep(2000);
System.out.println("Select orange by value");
sel.selectByValue("orange");

Thread.sleep(2000);
System.out.println("De-select orange by value");
sel.deselectByValue("orange");

Thread.sleep(2000);
System.out.println("Select peach by index");
sel.selectByIndex(2);

Thread.sleep(2000);

System.out.println("Select Apple by visible text");

sel.selectByVisibleText("Apple");

Thread.sleep(2000);
System.out.println("Print all selected options");
List<WebElement> selectedOptions = sel.getAllSelectedOptions();
for (WebElement option : selectedOptions) {
System.out.println(option.getText());
}

Thread.sleep(2000);
System.out.println("De-select all selected options");
sel.deselectAll();
}

9. Working with hidden element

public void testLetsKodeIt() throws InterruptedException {

driver.get(baseUrl1);

WebElement textBox = driver.findElement(By.id("displayed-text"));


System.out.println("Text Box Displayed: " + textBox.isDisplayed());

Thread.sleep(3000);

WebElement hideButton = driver.findElement(By.id("hide-textbox"));


hideButton.click();
System.out.println("Clicked on hide button");
System.out.println("Text Box Displayed: " + textBox.isDisplayed());

Thread.sleep(3000);

// Added code to scroll up because the element was hiding behind the top
navigation menu
// You will learn about scrolling
js.executeScript("window.scrollBy(0, -190);");
WebElement showButton = driver.findElement(By.id("show-textbox"));
showButton.click();
System.out.println("Clicked on show button");
System.out.println("Text Box Displayed: " + textBox.isDisplayed());
}
10. Profiles
What is Profile?
File where Firefox saves your personal information such as bookmarks, passwords, and user
preferences.
Multiple Firefox profiles can exist, each containing a separate set of preferences.

When starting Firefox in Selenium WebDriver, it starts new "anonymous" profile.

Why New Profile for Automation?


You might have the need of some plugins in your web application or some SSL certificate for
your application, which is not available by default in the anonymous profile.

It is nice to make a separate profile for automation, so as to not disturb your usual browser
settings.
A profile should be lightweight - it should only have settings, plugins that you need for
automation.

Where is the profile located on the System?


Windows XP / 2000 / Vista / 7 In the search box, type in: %APPDATA%\Mozilla\Firefox\
Profiles\ C:\Users\UserName\AppData\Roaming\Mozilla\Firefox\Profiles - Replace
Username
Mac OS X
~/Library/Application Support/Firefox/Profiles

Windows
1. At the top of the Firefox window, click on the File menu and then select Exit.
2. Press ‘ + R’ or click on the Windows Start Menu (bottom left button) and then select Run.
3. In the Run dialog box, type in: ‘firefox.exe -p' and then Click OK.

If the Profile Manager window does not appear, it may be possible that Firefox is opened in
the background. It needs to be closed; you can open the Task Manager to kill the process. If
it still does not open then you may need to specify the full path of the Firefox program.

32-bit Windows: "C:Program FilesMozilla Firefoxfirefox.exe" -p


64-bit Windows: "C:Program Files (x86)Mozilla Firefoxfirefox.exe" –p

public class ProfilesDemo {

public static void main(String[] args) {


System.setProperty("webdriver.gecko.driver",

"/Users/atomar/Documents/workspace_personal/libs/geckodriver");
String baseURL = "http://www.letskodeit.com";
WebDriver driver;

ProfilesIni profile = new ProfilesIni();


FirefoxProfile fxProfile = profile.getProfile("automationprofile");
FirefoxOptions options = new FirefoxOptions();
options.setProfile(fxProfile);

driver = new FirefoxDriver(options);


driver.manage().window().maximize();
driver.get(baseURL);
}
}

We can add chrome extention in our program


ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("/Users/<username>/Library/Application
Support/Google/Chrome/Default/Extensions/aapocclcgogkmnckokdopfmhonfmgoek/
0.9_0.crx"));

driver = new ChromeDriver(options);

11. Useful Methods.

1. How to get the text on the element


Element.getText();
2. How to get attribute on the element
Element.getAttribute(attribute name);

12. Waits in selenium


Implicit Wait: If elements are not immediately available, an implicit wait tells Web Driver to
poll the DOM for a certain amount of time. The default setting is 0. Once set, the implicit
wait is set for the duration of the Web Driver object. This means that we can tell Selenium
WebDriver that we would like it to wait for a certain amount of time before throwing an
exception that it cannot find the element on the page.
Explicit Wait: It is the custom one. It will be used if we want the execution to wait for some
time until some condition achieved. An explicit waits is what we can define to wait for a
certain condition to occur before proceeding further in the code. These are the available
expected conditions:
• alertIsPresent
• elementSelectionStateToBe
• elementToBeClickable
• elementToBeSelected
• frameToBeAvailableAndSwitchToIt
• invisibilityOfElementLocated
• presenceOfElementLocated
• textToBePresentInElementLocated
• textToBePresentInElementValue
• titleContains
• titleIs
• visibilityOfElementLocated

WebDriverWait wait = new WebDriverWait(driver, timeout); element =


wait.until( ExpectedConditions.elementToBeClickable(locator));

Implicit Wait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));

Explicit Wait
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(3));

WebElement emailField = wait.until(

ExpectedConditions.visibilityOfElementLocated(By.id("user_email")));

Interview Questions
What are the different types of waits available in Selenium WebDriver With Java
Programming Language?

There are 2 types of wait


• Implicit Wait
• Explicit Wait

What is the difference between implicit wait and explicit wait?

Implicit Wait: If elements are not immediately available, an implicit wait tells Web Driver to
poll the DOM for a certain amount of time. The default setting is 0. Once set, the implicit
wait is set for the duration of the Web Driver object. This means that we can tell Selenium
WebDriver that we would like it to wait for a certain amount of time before throwing an
exception that it cannot find the element on the page.

Explicit Wait: It is the custom one. It will be used if we want the execution to wait for some
time until some condition achieved. There can be instance when a particular element takes
more than a minute to load. In that case you definitely not like to set a huge time to Implicit
wait, as if you do this your browser will going to wait for the same time for every element.
To avoid that situation you can simply put a separate time on the required element only. By
following this your browser implicit wait time would be short for every element and it would
be large for specific element.

What are some of the expected conditions?


These are the available expected conditions:
• elementToBeClickable
• presenceOfElementLocated
• titleContains
13. How to take screenshot.

public class ScreenshotsDemo {


private WebDriver driver;
private String baseUrl;

@Before
public void setUp() throws Exception {
driver = new ChromeDriver();
baseUrl = "https://www.facebook.com/";
// Maximize the browser's window
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}

@Test
public void testScreenshots() throws Exception {
driver.get(baseUrl);
driver.findElement(By.xpath("//input[@data-
testid='royal_login_button']")).click();
}

@After
public void tearDown() throws Exception {
String filename = getRandomString(10) + ".png";
String directory = System.getProperty("user.dir") + "//screenshots//";
File sourceFile =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(sourceFile, new File(directory + filename));
driver.quit();
}

public static String getRandomString(int length) {


StringBuilder sb = new StringBuilder();
String characters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
for (int i = 0; i < length; i++) {
int index = (int)(Math.random() * characters.length());
sb.append(characters.charAt(index));
}
return sb.toString();
}
}
14. JavaScriptExecutor
private WebDriver driver;
String baseUrl;
private JavascriptExecutor js;
js = (JavascriptExecutor) driver;
// driver.get(baseUrl);
js.executeScript("window.location =url;");

// Finding element
// WebElement textBox = driver.findElement(By.id("name"));
WebElement textBox = (WebElement) js.executeScript("return
document.getElementById('name');");

// Size of window
long height = (Long) js.executeScript("return window.innerHeight;");
long width = (Long) js.executeScript("return window.innerWidth;");

// Scroll Down
js.executeScript("window.scrollBy(0, 1900);");

// Scroll Up
js.executeScript("window.scrollBy(0, -1900);");

// Scroll Element Into View


WebElement element = driver.findElement(By.id("mousehover"));
js.executeScript("arguments[0].scrollIntoView(true);", element);

js.executeScript("window.scrollBy(0, -190);");

//click on element
WebElement checkBoxElement = driver.findElement(By.id("bmwcheck"));
js.executeScript("arguments[0].click();", checkBoxElement);

15. Switch

Window
// Get the handle
String parentHandle = driver.getWindowHandle();

// Get all handles


Set<String> handles = driver.getWindowHandles();

// Switching between handles


for (String handle: handles) {
System.out.println(handle);
if (!handle.equals(parentHandle)) {
driver.switchTo().window(handle);
Thread.sleep(2000);
WebElement searchBox = driver.findElement(By.id("search-
courses"));
searchBox.sendKeys("python");
Thread.sleep(2000);
driver.close();
break;
}
}
// Switch back to the parent window
driver.switchTo().window(parentHandle);
driver.findElement(By.id("name")).sendKeys("Test Successful");

Iframe:

// Switch to frame by Id
driver.switchTo().frame("courses-iframe");

// Switch to frame by name


driver.switchTo().frame("iframe-name");

// Switch to frame by numbers


driver.switchTo().frame(0);

16. Ale
Alert alert = driver.switchTo().alert();
alert.accept();
alert.dismiss();

17. Action Class

//Mouse Hover Actions on element


Actions action = new Actions(driver);
action.moveToElement(mainElement).perform();

//Mouse Hover Actions on element and click


Actions action = new Actions(driver )
action.moveToElement(subElement).click().perform();

// Drag and Drop- Action class


Actions action = new Actions(driver);
action.dragAndDrop(fromElement, toElement).build().perform();

// Click and hold, move to element, release, build and perform


Actions action = new Actions(driver);
action.clickAndHold(fromElement).moveToElement(toElement).release().build().perform();

//Slider Using the actions class


WebElement element = driver.findElement(By.xpath("//div[@id='slider']/span"));
Actions action = new Actions(driver);
ction.dragAndDropBy(element, 100, 0).perform();
18. Key Press events
We can use press keyboard using key.
driver.findElement(By.id("user_email")).sendKeys(Keys.TAB);
driver.findElement(By.name("commit")).sendKeys(Keys.ENTER);

driver.findElement(By.id("openwindow")).sendKeys(Keys.COMMAND + "a");
driver.findElement(By.id("openwindow")).sendKeys(Keys.chord(Keys.COMMAND, "a"));

We can do above using Actions class


Actions action = new Actions(driver);
action.keyDown(Keys.COMMAND).sendKeys("a").keyUp(Keys.COMMAND).perform();

19. Exception in Selenium( Most Famous)

1.No Such Element Exception


2.Element Not Clickable At Point Exception
3.Stale Element Exception Exception
4. Element Not Interactable Exception

1.No Such Element Exception


1. Timing Issues
2. Incorrect locator or type of locator
3. Element is in iFrame
2. Element Not Clickable At Point Exception
1. Element is loaded in DOM, but it is overlapped by another element.
2. Element is not visible because of another element
3. Stale Element Exception Exception
1. If page changes/reloads DOM is rebuilt, previously found elements become stale.
2. In dropdown when one item is selected other goes stale, if we forget to use break;
statement we will get stale element exception

4. Element Not Interactable Exception

1.Element is in disabled or hidden state

2. Performing an unsupported action on an element

20. Log4j 2.x version


Log4j API that can be used to create logging infra structure in your tests.

Why logging is important in any application?

Logging is very important to any application. It helps us is quick debugging, easy


maintenance by collecting information about the execution.

Advantages of Log4j
• Log4j allows you to have a very good logging infrastructure with minimal efforts.
• Allows categorizing logs at different logging levels (Trace, Debug, Info, Warn, Error and
Fatal).
• Provides control to format the output of the logs.
• It has multiple appenders styles, which allows to direct logs to different outputs styles like
a file, console or a database.
• Logging can be set at runtime using configuration files.

Log4j consists of three main components

Logger This is a class, which helps you log information at different logging levels.

Appenders Appenders are objects, which help Logger objects write logs to different outputs.
Appenders can specify a file, console or a database as the output location.

Layouts Layout class helps us define how the log information should appear in the outputs.

https://logging.apache.org/log4j/2.0/download.html
https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core/2.7
https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api/2.7

Log4j will check the system property “log4j.configurationFile” for the configuration file path.

In case no system property is defined the configuration order takes below precedence:
• Property ConfigurationFactory will look for log4j2-test.properties in the classpath.
• YAML ConfigurationFactory will look for log4j2-test.yaml or log4j2-test.yml in the
classpath.
• JSON ConfigurationFactory will look for log4j2-test.jsn or log4j2-test.json in the classpath. •
XML ConfigurationFactory will look for log4j2-test.xml in the classpath.
• Property ConfigurationFactory will look for log4j2.properties on the classpath
• YAML ConfigurationFactory will look for log4j2.yml or log4j2.yaml in the classpath.
• JSON ConfigurationFactory will look for log4j2.jsn or log4j2.json in the classpath.
• XML ConfigurationFactory will look for log4j2.xml in the classpath.
• If no configuration file was provided, the DefaultConfiguration takes place and that would
lead you for set of default behaviors:
o Root logger will be used.
o Root logger level will be set to ERROR.
o Root logger will propagate logging messages into console.
o PatternLayout is set to be %d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n

• ALL
• TRACE
• DEBUG
• INFO
• WARN
• ERROR
• FATAL
private static final Logger log = LogManager.getLogger(LoggingDemo.class.getName());
log.debug("Debug Message Logged");
log.error("Error Message Logged");
log.fatal("Fatal Message Logged");

21. TestNG Introduction

TestNG is a testing framework inspired from JUnit and NUnit with more functionality added
to make execution more efficient and powerful. It is an open source automated testing
framework.

TestNG eliminates most of the limitations of the older framework and gives the developer
the ability to write more flexible and powerful tests with help of easy annotations, grouping,
sequencing & parameterizing.

Benefits of TestNG Major advantages of testing are:


• Logs can be generated
• Annotations make code efficient and easy to manage
• Ability to produce HTML Reports of execution
• Test cases can be Grouped & Prioritized
• Parallel testing is possible
• Data Parameterization is possible

Annotations in TestNG
@BeforeSuite: Method with this annotation will run before all tests in the test suite
@AfterSuite: Method with this annotation will run after all tests in the test suite
@BeforeTest: Method with this annotation will run before each and every test method with
tag in xml file
@AfterTest: Method with this annotation will run after each and every test method with tag
in xml file
@BeforeClass: Method with this annotation will run before first test method in current class
@AfterClass: Method with this annotation will run after last test method in current class
@BeforeMethod: Method with this annotation will run before each test method
@AfterMethod: Method with this annotation will run after each test method
@Test: The annotated method is a part of a test case.

Benefits of using annotations

1. TestNG identifies the methods that it is interested in by looking up annotations. Hence


method names are not restricted to any pattern or format.
2. We can pass additional parameters to annotations.
3. Annotations are strongly typed, so the compiler will flag any mistakes right away.
4. Test classes no longer need to extend anything (such as Test Case, for JUnit 3).
Data Provider

public class TestNG_DataProviders {

@DataProvider(name="inputs")

public Object[][] getData() {

return new Object[][] {

{"bmw", "m3"},

{"audi", "a6"},

{"benz", "c300"}

};

@Test(dataProvider="inputs")

public void testMethod1(String input1, String input2) {

System.out.println("Input 1: " + input1);

System.out.println("Input 2: " + input2);

You might also like