Saturday, July 30, 2022

Selenium Tests using Data Provider and TestNG

 package coaching;


import java.io.File;

import java.io.FileInputStream;

import java.io.FileReader;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.time.Duration;

import java.util.Date;

import java.util.Properties;


import org.apache.commons.io.FileUtils;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.xssf.usermodel.XSSFRow;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.openqa.selenium.By;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.ITestResult;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.AfterTest;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.BeforeTest;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;


import com.relevantcodes.extentreports.ExtentReports;

import com.relevantcodes.extentreports.ExtentTest;

import com.relevantcodes.extentreports.LogStatus;


public class Login_Page {

public WebDriver driver;

public ExtentReports extent;

public ExtentTest extentTest; //helps to generate the logs in test report.

@BeforeTest

public void setExtent(){

// initialize the HtmlReporter

extent = new ExtentReports("./src/test/resources/Reports/LoginPageReport.html", true); // true - new data insert into report,false-append the old data

//To add system or environment info by using the addSystemInfo method.

extent.addSystemInfo("User Name", "Suriya");

extent.addSystemInfo("Environment", "Automation Testing");

extent.addSystemInfo("Application","Learning Online Course "); 

extent.addSystemInfo("Test Scenario","Login Functionality");


}

@AfterTest

public void endReport(){


extent.flush(); // Flush method is used to erase any previous data on the report and create a new report.

//extent.close(); 

}

public static String getScreenshot(WebDriver driver, String screenshotName) throws IOException{

String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());

TakesScreenshot ts = (TakesScreenshot) driver;

File source = ts.getScreenshotAs(OutputType.FILE);

// after execution, you could see a folder "FailedTestsScreenshots"

// under src folder

String destination = System.getProperty("user.dir") + "/FailedTestsScreenshots/" + screenshotName + dateName

+ ".png";

File finalDestination = new File(destination);

FileUtils.copyFile(source, finalDestination);

return destination;

}

@BeforeMethod

public void setup() throws InterruptedException, IOException {


System.setProperty("webdriver.chrome.driver", "F:\\Suriya\\chromedriver.exe");

driver = new ChromeDriver();

driver.manage().window().maximize();

driver.manage().deleteAllCookies();

driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));

driver.get("URL");

}

@Test (dataProvider = "getData") 

public void login(String Username, String Password) {

extentTest = extent.startTest("Enter username and password");

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));

WebElement username = driver.findElement(By.id("userName"));

username.sendKeys(Username);

WebElement password = driver.findElement(By.id("pwd"));

password.sendKeys(Password);

WebElement login = driver.findElement(By.cssSelector(".btn:nth-child(3)"));

login.click();

}

@DataProvider(name = "getData") 

// Declare a method whose return type is an array of object. 

    public Object[ ][ ] dataProviderMethod() 

    {

// Create an object of an array object and declare parameters 3 and 2. 

// 3 represents the number of times your test has to be repeated. 

// 2 represents the number of parameters in test data. Here, we are providing two parameters. 

     Object[ ][ ] data = new Object[3][2]; 


// 1st row. 

      data[0][0] = "John"; 

      data[0][1] = "23RYRTE7E5"; 


// 2nd row. 

     data[1][0] = "Sanjana"; 

     data[1][1] = "40EEUE5"; 


// 3rd row. 

     data[2][0] = "Deep"; 

     data[2][1] = "01E575E"; 

      return data; 

   } 

@AfterMethod

public void Down(ITestResult result) throws IOException{


if(result.getStatus()==ITestResult.FAILURE){

extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS "+result.getName()); //to add name in extent report

extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS "+result.getThrowable()); //to add error/exception in extent report


String screenshotPath = getScreenshot(driver, result.getName());

extentTest.log(LogStatus.FAIL, extentTest.addScreenCapture(screenshotPath)); //to add screenshot in extent report

//extentTest.log(LogStatus.FAIL, extentTest.addScreencast(screenshotPath)); //to add screencast/video in extent report

}

else if(result.getStatus()==ITestResult.SKIP){

extentTest.log(LogStatus.SKIP, "Test Case SKIPPED IS " + result.getName());

}

else if(result.getStatus()==ITestResult.SUCCESS){

extentTest.log(LogStatus.PASS, "Test Case PASSED IS " + result.getName());


}



extent.endTest(extentTest); //ending test and ends the current test and prepare to create html report

driver.quit();

}

}



Tuesday, June 28, 2022

Selenium Interview Questions and Answers - PART 1

1. What is Selenium?

  •  Selenium is an automation testing tool that is used for automating web-based applications.
  •  It supports multiple browsers, programming languages, and platforms.

2. What are the different forms of selenium?

  •  Selenium WebDriver - It is used to automate web applications using browser methods.
  •  Selenium IDE - It is a plugin that works on record and playback principles.
  •  Selenium RC - Selenium Remote Control(RC) is officially deprecated by Selenium and it used to work on javascript to automate web applications.
  •  Selenium Grid - Allows selenium tests to run in parallel across multiple machines.

3. Advantages of selenium?

  •  Selenium is open source and free to use without any licensing cost.
  •  It supports multiple languages like java, ruby, python, etc.
  •  It supports multi-browser testing.
  •  Using the selenium ide component, non-programmers can also write automation scripts.

4. Limitations of selenium?

  •  We cannot test the desktop applications using selenium.
  •  We cannot test web services using selenium.

5. Which browsers/drivers are supported by the selenium web driver?

 Google chrome - ChromeDriver

 Firefox - FireFoxDriver

 Internet Explorer - InternetExplorerDriver

 Safari - SafariDriver

6. What are the testing types supported by the selenium web driver?

  •  Selenium web driver can be used for performing automated functional and regression testing.

7.Different locators in selenium?

 id,xpath,cssSelector,className,tagName,name,linkText,partialLinkText

8.What is an XPath?

  •  Xpath or XML path is a query language for selecting nodes from XML documents.
  •  XPath is one of the locators supported by the selenium web driver.

 Types of XPath:

 absolute XPath

 relative XPath

9. How can we launch different browsers in the selenium web driver?

  •  By creating an instance of the driver of a particular browser

 WebDriver driver = new ChromeDriver();

10.What is the use of driver.get("url") and driver.navigate().to("url")command?

  •  Both driver. get("url") and driver.navigate().to("URL") commands are used to navigate to a URL passed as a parameter.

11. How can we type text in a textbox element using selenium?

  •  using the sendKeys() method we can type text in a textbox.

 WebElement text = driver.findElement(By.id("search"));

 text.sendKeys("suriya");

12. How we can clear a text written in a textbox?

  •  Using the clear() method we can delete the text written in a textbox.

 driver.findElement(By.id("elementLocator")).clear();

13. How to check a checkbox in selenium?

  •  the click() method used for clicking buttons or radio buttons can be used for checking checkboxes.

14. Difference between close and quit commands?

 driver.close() - used to close the current browser having focus.

 driver.quit() - used to close all the browser instances

15. Maximize browser window - driver.manage().window().maximiza();

16. Find the value - driver.findElement(By.id("locator")).getAttribute("value");

17. How to delete cookies in selenium?

 driver.manage().deleteAllCookies();

18. Double-click an element in selenium?

 Actions action = new Actions(driver);

 WebElement element = driver.findElement(By.id("elementid"));

 action.doubleClick(element).perform();

19. Right-click an element in selenium?

 Actions action = new Actions(driver);

 WebElement element = driver.findElement(By.id("elementid"));

 action.contextClick(element).perform();

20. How to fetch the current page URL in selenium?

 driver.getCurrentUrl();

21. How can we fetch the title of the page in selenium?

 driver.getTitle();

22. fetch the page source in selenium?

 driver.getPageSource();

Monday, June 20, 2022

JavaScriptExecutor in Selenium WebDriver

 JavaScript:

  •  JavaScript is a programming language that interacts with HTML DOM within the browser.

JavaScriptExecutor:

  •  JavaScript executor is an interface provided by Selenium that gives a mechanism to execute JavaScript through Selenium WebDriver.
  •  It provides two methods such as “executeScript” & “executeAsyncScript” to run JavaScript on the currently selected frame, window, or page.

Uses of JavaScriptExecutor:

  •  There are locators in Selenium WebDriver like ID, Class, XPath, etc., to work with elements on a web page.
  •  Sometimes these default Selenium locators may not work.
  •  JavaScriptExecutor is used to perform operations on a web page.
  •  JavascriptExecutor in Selenium enables the WebDriver to interact with HTML DOM within the browser.


1. Type Text in a Text Box

 JavascriptExecutor js = (JavascriptExecutor) driver;

 js.executeScript("document.getElementById('Email').value='suriya@gmail.com';");


2. To Click on a Button

 js.executeScript("document.getElementById('enter your element id').click();");


3. To refresh browser window using Javascript

 js.executeScript("history.go(0)");


4. To get the inner text of the entire webpage in Selenium

 String Text =  js.executeScript("return document.documentElement.innerText;").toString();

 System.out.println(Text);


5. To get the Title of our webpage

 String Text =  js.executeScript("return document.title;").toString();

 System.out.println(Text);


6. To get the URL of a webpage

 String Text =  js.executeScript("return document.URL;").toString();

 System.out.println(Text);


7. To perform Scroll on an application

 js.executeScript("window.scrollBy(0,500)");

Wednesday, May 25, 2022

Types of Software Testing

 Software Testing:

  •  The process of finding errors in the developed product.
  •  Testing the software whether it is working according to the requirement.


Two ways of Testing:

 1. Manual Testing

 2. Automation Testing


Manual Testing:

  •  Manual testing is verifying the software manually and finding errors without the intervention of any tools.
  •  The tester has to execute each test case one by one.
  •  They give input and manually verify the output.


Automation Testing:

  •  Automation Testing is testing the software with the help of some automation tools like Selenium.
  •  The code is run for automating tests and the input data is given to the tool.
  •  The output data is compared with the expected results.
  •  Automation testing is generally performed for repeated tasks so that time can be saved.


Levels of Testing:

 1. Unit Testing

 2. System Testing

 3. Integration Testing

 4. Acceptance Testing


1. Unit Testing:

  •  Unit testing is the first level of testing usually performed by the developers.

Advantage: Error can be detected at an early stage saving time and money to fix it.


2. System Testing:

  •  Complete application testing.
  •  Done by Testers.
  •  Black Box Testing Techniques.
  •  FRS and test case document.

System Testing Categories:

  •  Usability Testing
  •  Functional Testing
  •  Performance Testing
  •  Security Testing


3. Integration Testing:

  •  Combining/merging modules.
  •  Done by Developers.
  •  White box testing technique.

4. Acceptance Testing:

  •  Getting approval from the client.
  •  Done by the client.
  •  Satisfying client requirements.


Types of Testing:

 1. Functional Testing

 2. Non-Functional Testing


1. Functional Testing:

  •  Testing the behaviour of the application.
  •  Based on how well the system is working.

Alpha Testing:

  •  The application is tested for the first time.
  •  Done under the supervision of developers.

Beta Testing:

  •  The application is tested a second time.
  •  Before the final release of the software is released to users for testing.

Smoke Testing:

  •  Testing the primary functionality of the application.

Sanity Testing:

  •  Testing the minor functionality of the application.

Regression Testing:

  •  Testing the whole application to check whether new requirement changes affect previous functionality.

Retesting:

  •  Testing only the bugs fixed by the developers.


2. Non-Functional Testing:

  •  Based on how well the system is performed.
  •  Testing the performed to verify the non-functional requirements of the application.

Usability Testing:

  •  User Friendly
  •  Look and Feel
  •  Ease of use
  •  Speed in Interface
  •  Context Sensitiveness

Performance Testing:

  •  Load Testing
  •  Stress Testing
  •  Data/Volume Testing

Security Testing:

  •  Protecting from unauthorized access.

Compatibility Testing:

  •  OS Compatability - Testing in multiple OS.
  •  Browser Compatability - Testing in multiple Browsers.


Software Testing Interview Questions and Answers:

1. STLC - stands for Software Testing Life Cycle.

  Requirements and analysis, test planning, test design, test execution, error report, solving the error, re-test, test close.

2. Software Quality:

  •   Quality is ensured by two sets of activities. verification and validation.

  Verification - It involves activities like document review, test case review, walk-throughs, and inspections.

  Validation - It involves activities like functional testing and automation testing.

3. Workflow of Functional Testing:

  •   Create input values.
  •   Execute test cases.
  •   Compare actual and expected output.

4. Client Expectation:

  Completeness, correctness, quality.

5. Tester Responsibility: (Zero bugs and 100% quality)

  •   Execute test cases
  •   Positive and Negative Conditions.
  •   Manual or Automation tools.

 6. Error - Done by the developer in code

   Bug - Tester identifies the errors.

7. Quality - Meeting client requirements.

   Customer needs or expectations.

8. How to measure Quality:

  Functionality, Usability, Reliability, Performance, and Scalability.

9. Bug - unexpected or incorrect result.

10. Main Goal of Testing:

  Expected Result = Actual Result (Test Pass)

  Expected Result != Actual Result (Test Fail)

11. Severity - the impact of a bug on the software.

   Priority - is how soon a bug needs to be fixed.

Friday, May 20, 2022

Java Programming Examples

 1. Java Syntax:
package selenium;
public class Java_Examples {
  public static void main(String[] args) {
System.out.println("suriya parithy");
}
}

2. Data types and variables:
package selenium;
public class Java_Examples {
  public static void main(String[] args) {
  // type variableName = value;
  String name = "suriya";
  int myNum = 15;
  float myFloatNum = 5.99f;
  char myLetter = 'S';
  boolean myBool = true;
  
  System.out.println(name);
  System.out.println(myNum);
  System.out.println(myFloatNum);
  System.out.println(myLetter);
  System.out.println(myBool);
  }
}

3. Java Operators:
package selenium;
public class Java_Examples {
  public static void main(String[] args) {
  int sum1 =100 + 200;
  int sum2 = sum1 + 300;
  int x = 4;
  int y = 6;
  System.out.println(sum1);
  System.out.println(sum2);
  System.out.println(x-y);
  System.out.println(x == y); // returns false because 4 is not equal to 6
  System.out.println(x != y); // returns true because 4 is not equal to 6
  System.out.println(x > y); 
  System.out.println(x < y);
  System.out.println(x > 3 && x < 10); // returns true because 4 is greater than 3 AND 4 is less than 10
  System.out.println(x > 3 || x < 5); // returns true because one of the conditions are true(4 is greater than 3)
  }
}

4. Java Strings:
package selenium;
public class Java_Examples {
  public static void main(String[] args) {
  String name = "suriya parithy";
  System.out.println("The length of the name string is:" + name.length());
  System.out.println(name.toUpperCase()); // Outputs "SURIYA PARITHY"
  System.out.println(name.toLowerCase()); // Outputs "suriya parithy"
  }
}

5. Java Math:
package selenium;
public class Java_Examples {
  public static void main(String[] args) {
  System.out.println(Math.max(15, 20));
  System.out.println(Math.min(5, 10));
  System.out.println(Math.sqrt(64));
  }
}