Friday, January 31, 2020

Data Provider

TestNG Data Provider


- Testing the same piece of software, we can't be unfair to test it with just one set of data.
- we need to verify that our system is taking all set of combinations which it expected to support.
- So comes Parameterization in the picture.
- To pass multiple data to the application at runtime, we need to parameterize our test scripts.
- This concept which we achieve by parameterization is called Data Driven Testing.

We will go through the parameterization options in Selenium Webdriver - TestNG.

There are two ways by which we can achieve parameterization in TestNG
  1. With the help of Parameters annotation and TestNG XML file.
    TestNG: Parameterization using XML & DataProvider in Selenium
  2. With the help of DataProvider annotation.
    TestNG: Parameterization using XML & DataProvider in Selenium

TestNG Data Providers


package DataProviderfromprog;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Reporter;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class Dataproviderprac {

WebDriver driver;
WebElement uname;
WebElement pass;
WebElement btnlogin;

@BeforeMethod
public void setup() {
System.setProperty("Webdriver.chrome.driver", "C:\\Users\\Administrator\\Downloads\\chromedriver_win32 (1)");
driver = new ChromeDriver();
driver.get("http://demo.cs-cart.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);

}
@DataProvider(name="LoginData")
public Object[][] getLoginData(){
Object[][] data=new Object[2][2];
data[0][0]= "Ram";
data[0][1]="Ram123";
data[1][0]= "Sham";
data[1][1]="sham123";
return data;
}
@Test(dataProvider="LoginData")
public void singinwithdifferntusernamesAndPasswords(String username, String password) {
driver.findElement(By.xpath("//html//body//div[2]//div[4]//div[1]//div//div//div[3]//div//div[1]//a//i[2]" + "")).click();
Reporter.log("Clicked on My Account <br>", true);
//driver.findElement(By.xpath("//a[@class='cm-dialog-opener cm-dialog-auto-size ty-btn ty-btn__secondary']")).click();
//Reporter.log("Clicked on Sign In Button");
driver.findElement(By.xpath("//*[@id=\"login_main_login\"]")).clear();
driver.findElement(By.xpath("//*[@id=\"login_main_login\"]")).sendKeys(username);
Reporter.log("Entered username <br>", true);

driver.findElement(By.xpath("//*[@id=\"psw_main_login\"]")).clear();
driver.findElement(By.xpath("//*[@id=\"psw_main_login\"]")).sendKeys(password);
Reporter.log("E <br>", true);

driver.findElement(By.xpath("/html/body/div[2]/div[4]/div[3]/div/div[2]/div[1]/div/div/div/form/div[3]/div[1]/button")).click();
}
}


Data Provider using XLSX file:

Dependencies required to access data from xlsx file are : 


<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>


package DataProviderfromprog;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Reporter;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataProviderfromxls {
WebDriver driver;

WebElement uname;
WebElement pass;
WebElement btnlogin;
String filepath = "C:\\Users\\Administrator\\eclipse-workspace\\VisionDataprovider\\userpwd.xls";

@BeforeMethod
public void setup() {
System.setProperty("Webdriver.chrome.driver", "C:\\Users\\Administrator\\Downloads\\chromedriver_win32 (1)");
driver = new ChromeDriver();

driver.get("http://demo.cs-cart.com/");
driver.manage().window().maximize();
// driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

}

@Test(dataProvider = "logindataSupplier")
public void checkloginScenario(String username, String password) {

driver.findElement(
By.xpath("//html//body//div[2]//div[4]//div[1]//div//div//div[3]//div//div[1]//a//i[2]" + "")).click();
Reporter.log("Clicked on My Account <br>", true);

driver.findElement(By.xpath("//*[@id=\"login_main_login\"]")).clear();
uname = driver.findElement(By.xpath("//*[@id=\"login_main_login\"]"));
uname.sendKeys(username);
Reporter.log("Entered username <br>", true);

driver.findElement(By.xpath("//*[@id=\"psw_main_login\"]")).clear();
pass = driver.findElement(By.xpath("//*[@id=\"psw_main_login\"]"));
pass.sendKeys(password);
Reporter.log("E <br>", true);

driver.findElement(
By.xpath("/html/body/div[2]/div[4]/div[3]/div/div[2]/div[1]/div/div/div/form/div[3]/div[1]/button"))
.click();
}

@DataProvider(name = "logindataSupplier")
public Object[][] getlogintestdata() throws IOException {

FileInputStream fis = new FileInputStream(filepath);

XSSFWorkbook workbook = new XSSFWorkbook(fis);

XSSFSheet sheet = workbook.getSheetAt(0);

int rowcount = sheet.getLastRowNum();
System.out.println("rowcoun : " + rowcount);

int cellcount = sheet.getRow(0).getLastCellNum();
System.out.println("no of cells" + cellcount);

Object[][] testdata = new Object[rowcount][cellcount];

for (int i = 0; i < rowcount; i++) {
for (int j = 0; j < cellcount; j++) {

testdata[i][j] = sheet.getRow(i + 1).getCell(j).toString();

}

}

return testdata;

}
}



Summary:
  • Parameterization is require to create Data Driven Testing.
  • TestNG support two kinds of parameterization, using @Parameter+TestNG.xml and using@DataProvider
  • In @Parameter+TestNG.xml parameters can be placed in suite level and test level. If
    The Same parameter name is declared in both places; test level parameter will get preference over suit level parameter.
  • using @Parameter+TestNG.xml only one value can be set at a time, but @DataProvider return an 2d array of Object.
  • If DataProvider is present in the different class then the class where the test method resides,DataProvider should be static method.
  • There are two parameters supported by DataProvider are Method and ITestContext.

Tuesday, January 28, 2020

Selenium Java Interview Que & Ans Part-5

1) What are the advantages of using TestNG?
– It provides parallel execution of test methods
– It allows to define dependency of one test method over other method
– It allows to assign priority to test methods
– It allows grouping of test methods into test groups
– It has support for parameterizing test cases using @Parameters annotation
– It allows data driven testing using @DataProvider annotation
– It has different assertions that helps in checking the expected and actual results
– Detailed (HTML) reports
2) Can you arrange the below testng.xml tags from parent to child?
<test>
<suite>
<class>
<methods>
<classes>
  1. <suite><test><classes><class><methods>

3) What is the importance of testng.xml file?
TestNG.xml file is an XML file which contains all the Test configuration and this XML file can be used to run and organize our test.
4) What is TestNG Assert and list out common TestNG Assertions?
Asserts helps us to verify the conditions of the test and decide whether test has failed or passed. Some of the common assertions are:
– assertEqual(String actual,String expected)
– assertTrue(condition)
– assertFalse(condition)
5) What is Soft Assert in TestNG?
SoftAssert don’t throw an exception when an assert fails. The test execution will continue with the next step after the assert statement.
6) What is Hard Assert in TestNG?
Hard Assert throws an AssertException immediately when an assert statement fails and test suite continues with next @Test.
7) How to create Group of Groups in TestNG?
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
  3. <suite name="TestNG Sample Test Suite">
  4. <test name="TestNG Sample Test">
  5. <groups>
  6. <define name="include-groups">
  7. <include name="sanity" />
  8. <include name="integration" />
  9. </define>
  10. <define name="exclude-groups">
  11. <include name="pass" />
  12. <include name="fail" />
  13. </define>
  14. <run>
  15. <include name="include-groups" />
  16. <exclude name="exclude-groups" />
  17. </run>
  18. </groups>
  19. <classes>
  20. <class name="com.groups.TestNGGroupsExample" />
  21. </classes>
  22. </test>
  23. </suite>

8) How to exclude a particular test method from a test case execution using TestNG?
  1. <suite name="Sample Test Suite" verbose="1" >
  2. <test name="Sample Tests" >
  3. <classes>
  4. <class name="com.test.sample">
  5. <methods>
  6. <exclude name="TestA" />
  7. </methods>
  8. </class>
  9. </classes>
  10. </test>
  11. </suite>

9) How to exclude a particular group from a test case execution using TestNG?
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
  3. <suite name="Test Suite">
  4. <groups>
  5. <run>
  6. <exclude name="integration"></exclude>
  7. </run>
  8. </groups>
  9. <test name="Test">
  10. <classes>
  11. <class name="TestNGGroupsExample" />
  12. </classes>
  13. </test>
  14. </suite>

10) How to disable a test case in TestNG?
  1. @Test(enabled = false)
  2. public void test() {
  3. System.out.println("This test is disabled");
  4. }

11) How to ignore a test case in TestNG?
  1. @Test(enabled = false)
  2. public void test() {
  3. System.out.println("This test is ignored");
  4. }

12) What are the different ways to produce reports for TestNG results?
There are two ways to generate a report with TestNG −
Listeners − For implementing a listener class, the class has to implement the org.testng.ITestListener interface. These classes are notified at runtime by TestNG when the test starts, finishes, fails, skips, or passes.
Reporters − For implementing a reporting class, the class has to implement an org.testng.IReporter interface. These classes are called when the whole suite run ends. The object containing the information of the whole test run is passed to this class when called.
13) How to write regular expressions in testng.xml file to search @Test methods containing “smoke” keyword?
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
  3. <suite name="testSuite">
  4. <test name="test"> <classes>
  5. <class name="sample">
  6. <methods>
  7. <exclude name="smoke.*"/>
  8. </methods>
  9. </class>
  10. </classes>
  11. </test>
  12. </suite>

14) What is the time unit we specify in test suites and test cases?
Time unit is Milliseconds
15) List out various ways in which TestNG can be invoked?
– Command Line
– Maven
– IDE
16) How to run TestNG using command prompt?
  1. java -cp C:\Selenium\SampleTest\lib\*;C:\Selenium\SampleTest\bin org.testng.TestNG testng.xml

17) What is the use of @Test(invocationCount=x)?
The invocationcount attribute tells how many times TestNG should run a test method. In this example, the method testCase will be invoked ten times:
  1. @Test(invocationCount = 10)
  2. public void testCase(){
  3. System.out.println("Invocation method");
  4. }

18) What is the use of @Test(threadPoolSize=x)?
The threadPoolSize attribute tells TestNG to create a thread pool to run the test method via multiple threads. With thread pool, it will greatly decrease the running time of the test method.
Example: Start a thread pool, which contains 3 threads, and run the test method 3 times
  1. @Test(invocationCount = 3, threadPoolSize = 3)
  2. public void testThreadPools() {
  3. System.out.printf("Thread Id : %s%n", Thread.currentThread().getId());
  4. }

19) What does the test timeout mean in TestNG?
While running test methods there can be cases where certain test methods get struck or may take longer time than to complete the execution than the expected. We need to handle these type of cases by specifying Timeout and proceed to execute further test cases / methods
  1. @Test(timeOut=5000)
  2. public void executeTimeOut() throws InterruptedException{
  3. Thread.sleep(3000);
  4. }

20) What is JUnit?
JUnit is an open source Unit Testing Framework for JAVA. It is useful for Java Developers to write and run repeatable tests.
21) What are JUnit annotations?
– @Test
– @ParameterizedTest
– @RepeatedTest
– @TestFactory
– @TestTemplate
– @Disabled
– @Tag
– @AfterAll
– @BeforeAll
– @BeforeEach
– @AfterEach
– @TestInstance
22) What is TestNG and what is its use?
TestNG is a testing framework inspired from JUnit and NUnit but introducing some new functionalities that make it more powerful and easier to use. It is used for:
– Annotations
– Run your tests in arbitrarily big thread pools with various policies available
– Test that your code is multithread safe
– Flexible test configuration
– Support for data-driven testing
– Support for parameters
– Powerful execution model
– Supported by a variety of tools and plug-ins
– Embeds BeanShell for further flexibility
– Default JDK functions for runtime and logging
– Dependent methods for application server testing
23) How is TestNG better than JUnit?
– TestNG supports more annotations than Junit
– TestNG supports ordering of tests but Junit doesn’t
– TestNG supports various types of listeners using annotations but Junit doesn’t
– TestNG reports are better than Junit
24) How to set test case priority in TestNG?
  1. @Test (priority=1)
  2. public void openBrowser() {
  3. driver = new FirefoxDriver();
  4. }
  5. @Test (priority=2)
  6. public void launchGoogle() {
  7. driver.get("http://www.google.co.in");
  8. }

25) How to pass parameters through testng.xml to a test case?
  1. public class ParameterizedTest {
  2. @Test
  3. @Parameters("name")
  4. public void parameterTest(String name) {
  5. System.out.println("Parameterized value is : " + name);
  6. }
  7. }

  1. <?xml version = "1.0" encoding = "UTF-8"?>
  2. <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
  3. <suite name = "Suite1">
  4. <test name = "test1">
  5. <parameter name = "name" value="bijan"/>
  6. <classes>
  7. <class name = "ParameterizedTest" />
  8. </classes>
  9. </test>
  10. </suite>

String

  Java String  class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), re...