Friday, May 8, 2015

TestNG Listeners

 TestNG provides a bunch of listeners as a part of its testing environment. These listeners are as follows:

  1. ITestListener
  2. IRetryListener
  3. IReporter
  4. ISuiteListener
  5. IInvokedMethod
  6. IHookable
  7. IConfigurationListener
  8. IConfigurableListener
  9. IAnnotationTransformer
  10. IExecution
  11. IMethodInterceptor

Retry Failed Tests in TestNG

TestNG provides various listeners to customize our needs. One such powerful listener is IRetryListener using which you can retry a test case multiple times before declaring it as Failed.

If you see a failure can just automatically rerun the test to make sure that the test is consistently failing. this way it reduces false failures because of random issues and you spend more time debugging true failures.

IRetryListener interface has only one method public boolean retry(ITestResult result);

This method will be called whenever a test method fails. You can get the details of the test from ITestResult input argument to this method. This method implementation should return true if you want to re-execute your failed test and false if you don't want to re-execute your test.

Page load using JavascriptExecutor



public static boolean waitForPageLoad(WebDriver driver, int timeout){
ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>(){
public Boolean apply(WebDriver driver){
return ((JavascriptExecutor)driver).executeScript("return document.readyState");
}
};
WebDriverWait wait = new WebDriverWait(driver, timeout);
return wait.until(pageLoadCondition); 
}

Reading Excel Data using Fillo API in Selenium

Fillo is an excel API for Java and is used to query both xls and xlsx files.

It supports SELECT, UPDATE, INSERT, and DELETE queries with or without clause. 

Maven Dependency

<dependency>
  <groupId>com.codoid.products</groupId>
  <artifactId>fillo</artifactId>
  <version>1.21</version>
</dependency>

Select:

Fillo fillo = new Fillo();
Connection con = new fillo.getConnection("c:\test.xlsx");
sQuery = "Select * from Sheet1 where ID=111 and Department = Finance";
Recordset rs = con.executeQuery(sQuery);
While(rs.next()){
System.out.println(rs.getField("Name"))
}
rs.close();
connection.close();

Update:

Fillo fillo = new Fillo();

Connection con = new fillo.getConnection("c:\test.xlsx");
sQuery = "Update Sheet1 Set Salary = 120000 where ID=111 and Department = Finance";
Recordset rs = con.executeQuery(sQuery);
While(rs.next()){
System.out.println(rs.getField("Name"))
}
rs.close();
connection.close();

Insert:

Fillo fillo = new Fillo();
Connection con = new fillo.getConnection("c:\test.xlsx");
sQuery = "Insert into Sheet1(Name, Department, Salary) Values('Bala','Finance', 120000)";
Recordset rs = con.executeQuery(sQuery);
While(rs.next()){
System.out.println(rs.getField("Name"))
}
rs.close();
connection.close();

Multiple Where conditions:

Recordset recordset=connection.executeQuery("Select * from Sheet1 where column1=value1 and column2=value2 and column3=value3");

Where method:

Recordset recordset=connection.executeQuery("Select * from Sheet1").where("ID=100").where("name='John'");

LIKE Operator:

Recordset recordset=connection.executeQuery("Select * from Sheet1 where Name like 'Cod%'");

Set table starting row and column:

System.setProperty("ROW", "5");//Table start row
System.setProperty("COLUMN", "3");//Table start column
Fillo fillo=new Fillo();
Connection connection=fillo.getConnection(strFile);

Get all column names:

rs.getFieldNames()

Get row count:

rs.getCount()


Working with Microsoft Excel in Java

Apache POI is an open-source Java-based library that can be used to handle the Microsoft Office Document by using Java-based programming language.


Follow all the steps for reading the Excel sheet using Apache POI API







Exception Handling in Java

An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases, we get a system-generated error message. However, the exception can be handled in Java. By handling the exceptions, we can provide a meaningful message to the user about the issue rather than a system-generated message, which may not be understandable by the user.

Exception handling ensures that the flow of the program doesn't break when an exception occurs. For example, if a program has a bunch of statements and an exception occurs midway after executing certain statements then the statements after the exception will not be executed and the program will terminate abruptly.

By handling we make sure that all the statements execute and the flow of the program doesn't break.

Hierarchy of Java Exception classes




Type of Exceptions:
  1. Checked Exception
  2. Unchecked Exception

Check Exceptions: All exceptions other than Runtime Exceptions are known as Checked Exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. If these checked exceptions are not handled in the program, you will get a compilation error. For example, IOException, SQLException, ClassNotFoundException.

Unchecked Exceptions: Runtime Exceptions are known as Unchecked Exceptions. These exceptions are not checked at compile time so the compiler does not check whether the programmer has handled them or not but it is the responsibility of the programmer to handle the unchecked exceptions and provide a safe exit. For example, ArithematicExcpetion, ArrayIndexOutOfBoundsException, NullPointerException etc.

Try Catch in Java – Exception handling

Try Catch block contains set of statements where an exception may occur. A try block is always followed by a catch block, which handles the exception that occurs in associated try block. A try block must followed by catch blocks or finally block or both.

A catch block is where you handle the exceptions, the block must follow the try block. A single try block can have several catch blocks associated with it. You can catch different exceptions in different catch blocks. When an exception occurs in try block, the corresponding catch block that handles the particular exception executes. For example if an arithematic exception occurs in try block then the statements enclosed in catch block for arithematic exception executes.

try
{
     //statements that may cause an exception
}
catch (exception(type) e(object))‏
{
     //error handling code
}




Thursday, May 7, 2015

Interview Questions

  1. Explain the UFT automation framework? Hybrid/Keyword/Data-driven?
  2. How to load the function library at run-time?
  3. Difference between ExecuteFile and LoadFunctionLibrary functions?
  4. Explain AOM in UFT?
  5. How to zoom in or out of the browser in Selenium?
  6. How to execute JavaScript in Selenium?
  7. Explain waits in Selenium?
  8. How to handle multiple windows?
  9. How to handle window popup in Selenium?




Wednesday, May 6, 2015

Select an item from dropdown in Selenium

Selenium provides 3 methods:

  1. selectByIndex
  2. selectByVisibleText
  3. selectByValue
eDropdown = driver.findElement(By.xpath(""));
Select select = new Select(eDropdown);
select.selectByIndex(2);
select.selectByVisibleText("Ottawa")
select.selectByValue("ON");

Selenium Waits

Waits are extremely important in Selenium. 

Selenium provides 3 wait types:

  1. implicitwaits
  2. explicitwaits
  3. fluentwaits

Implicitwaits apply globally to every find element.

driver.manage().timeout().implicitwaits(30, TimeUnit.SECONDS);

Explicitwaits only apply per specific action or condition.

Explicit waits check the application every 500 ms to check for the condition of the wait to be true.

WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath(""));

Similar to explicit wait, fluentwaits only apply per specific action or condition.

Fluent waits require that you define the wait between checks of the application for an object or condition to be true and also the overall timeout of the transaction. In addition, you can tell fluent wait to not to throw an exception when it didnt find an object.

FluentWait wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(2, TimeUnit.SECONDS)
.ignoring(Exception.class);
WebElement el = wait.until(new Function<WebDriver, WebElement>(){
    public WebElement apply(WebDriver driver){
        return driver.findElement(By.xpath("");
    }});


Page Load Timeout in Selenium

Page load timeout is one of the timeouts mechanism in Selenium and it focuses on the time a webpage is loaded. 

The page load timeout limits the time that the script allows for a web page to be loaded. 

If the page is loaded within the time, then the script continues further execution. 

If the page is not loaded within the timeout, then the script will be stopped by a TimeoutException.

This timeout setting will remain in force for the remainder of the script (until changed) and will affect any calls that generate a new web page. This includes the get() method. However, the timeout may be delayed until the first findElement() call for the new page, since the navigation method may return asynchronously.

As a result, when using the timeout, webpage navigation should be executed under the control of try-catch clauses that catch the TimeoutException. For example:

driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);

TestNG parameters

TestNG Parameterization is used to pass parameters to tests as arguments. This is supported by using the TestNG @Parameters annotation.

1. Using @Parameters

2. Using @DataProvider


We can pass string types using @Parameters annotation to the test methods at run-time.

@Parameters ({"param-name"})
@Test
public void TestOne(String param){
}


@Parameters annotation can be used with the following annotation methods:

@BeforeXXX
@AfterXXX
@Factory
@Test

@Parameters can be used to initialize variables and use them in a class or test or maybe for the whole test suite execution.

How to handle multiple windows in Selenium?

Multiple web windows or tabs can be handled using window handlers and javascript executor.

Window handle is a unique identifier of the browser window. 

String strCurrentHandle = driver.getWindowHandle() : To get the window handle of the current browser window

Set<String> strHandles = driver.getWindowHandles() : To get all the window handles of browser windows opened. It returns set of handles.

String strPrevHandle = driver.getWindowHandle();
driver.findElement(By.xpath("//a[@id='link']");
Set<String> strHandles = driver.getWindowHandles();
for(String strHandle : strHandles){
    if(! strHandle.equalIgnoreCase(strPrevHandle)){
        driver.switchTo.window(strHandle)
        System.out.println(driver.getTitle());
        driver.close();
    }
}

driver.switchTo.window(strPrevHandle);

How to handle Alerts and Popups in Selenium?

 Handling alert

1. accept()

driver.switchTo().alert().accept();

2. dismiss()

driver.switchTo().alert().dismiss();

3. sendKeys()

driver.switchTo().alert().sendKeys("hello");

4. getText()

driver.switchTo().alert().getText();


Tuesday, May 5, 2015

How to run Cucumber from CommandLine

 

Running the tests or features from the command line or terminal without using the IDE or GUI.

Why

No dependency on IDE or GUI

Useful in integrations with other processes like CI/CD or deployment or release process. It will be easier and faster with command-line execution. It also consumes less memory.

When:

Whenever using CI tools like Jenkins
Whenever you need any batch or scheduled execution

Open command line
Navigate to project directory (cd "path")
mvn test

By default mvn test runs the files with naming syntax as below:
**/*Test*.java
**/Test*.java
**/OrderTest.java

Hence keep this naming convention only for the cucumber runner file. It will be run when execute the command mvn test from the command line.

CucumberOptions from command line:

1. Running a feature

mvn test -Dcucumber.options="src\test\resources\features\demo.feature"

2. Running a scenario in a feature file

mvn test -Dcucumber.options="src\test\resources\features\demo.feature:6"

3. Running with tags:

mvn test -Dcucumber.options="--tags @regression"

Or

mvn test -Dcucumber.options="-t @regression"

4. Reports

mvn test -Dcucumber.options="--plugin html:target/HtmlReport"

Or

mvn test -Dcucumber.options="-p html:target/HtmlReport"

5. Multiple options

mvn test -Dcucumber.options="src\test\resources\features\demo.feature:6" -Dcucumber.options="-p html:target/HtmlReports"


Background in Cucumber

Background in Cucumber is used to define a step or series of steps that are common across tests or scenarios within the feature file. 

A Background steps is run before every scenario in the feature file.

For example, two scenarios are listed below:

Scenario 1: Purchase order creation
Step 1: Launch the eCommerce website
Step 2: Login into website
Step 3: Search for a product
Step 4: Add to Cart
Step 5: Payment
Step 6: Submit order

Scenario 2: Update existing Purchase order
Step 1: Launch the eCommerce website
Step 2: Login into website
Step 3: Search for existing order
Step 4: Add new product
Step 5: Submit order

Step 1 and Step 2 are common steps in these two scenarios. So It recommends defining these common steps under the Background section, which will be run for each scenario in the feature file. 

Feature: Standard Purchase order 

Background:
Given Launch the eCommerce website
And Login into website
Scenario: Purchase order creation
Then Search for a product
And Add to Cart
And Payment
When Submit order
Scenario: Update existing Purchase order
Then Search for existing order
And Add new product
When Submit order

Monday, May 4, 2015

Scroll Operations using Javascript Executor in Selenium WebDriver

  1. ScrollIntoView
  2. ScrollTo
  3. ScrollBy

scrollIntoView() method scrolls the element's parent container such that the element on which scrollIntoView() is called is visible to the user.

WebElement footer = driver.findElement(By.cssSelector("#footerContainer"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView()", footer);

Zoom in and out using Selenium

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("document.body.style.zoom = '150%';");

js.executeScript("document.body.style.zoom = '70%';");

js.executeScript("document.body.style.zoom = '100%';");

Selenium 3 vs Selenium 4