I am working with excel using selenium web driver where username and password is passed is taken from excel and passed to application,pass/fail status is written back to excel.During exceptions such as no element found etc the execution stops. How to continue execution from the point where it stopped in the excel. Following is my code:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.UnreachableBrowserException;
public class Checkbox2 {
static WebDriver driver;
private static String filePath = "C:\\TEST DATA\\Users\\test.xlsx";
private static String sheetName = "Sheet1";
static File fl= new File(filePath);
public static void main(String[] args) throws InterruptedException, EncryptedDocumentException, InvalidFormatException
{
System.setProperty("webdriver.firefox.bin", "C:\\Users\\vijayab\\AppData\\Local\\Mozilla Firefox\\firefox.exe");
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("https://qa-bnymellon.correctnet.com/bnymellon/release10/me.get?DPS.home");
// driver.findElement(By.xpath("html/body/div[4]/div/div/div[1]/a[1]")).click();
try {
FileInputStream fis = new FileInputStream("C:\\Users\\vijayab\\Documents\\Work\\TEST DATA\\Users\\test.xlsx");
Workbook wb;
wb = WorkbookFactory.create(fis);
Sheet sheet = wb.getSheet("Sheet1");
for(int count=0;count<=sheet.getLastRowNum();count++)
{
Row row = sheet.getRow(count);
System.out.println("\n----------------------------");
System.out.println("Running test case " + count);
runTest(count, sheet, row.getCell(0).toString(),row.getCell(1).toString(),row,wb);
}
fis.close();
driver.close();// Closing the firefox driver instance
} catch (IOException e) {
System.out.println("Test data file not found");
}
}
public static void runTest(int count,Sheet sheet,String name,String mailid, Row row, Workbook wb) throws InterruptedException, InvalidFormatException, IOException
{
System.out.println("Inputing name: "+name+" and mailid: "+mailid);
driver.findElement(By.name("USERNAME")).sendKeys(name);
driver.findElement(By.name("PASSWORD")).sendKeys(mailid);
driver.findElement(By.name("SIGNIN")).click();
//driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
try{
if(driver.findElements(By.name("loginForm")).size() == 0){
System.out.println("Valid credentials"+count);
driver.findElement(By.name("DISCLAIMER")).click();
driver.findElement(By.id("ACCOUNTDOCUMENTS")).click();
driver.findElement(By.xpath("//*[contains(text(),'Account Profile')]")).click();
Thread.sleep(3000);
driver.switchTo().frame("FDX1");
driver.switchTo().frame("frame2-1");
Thread.sleep(4000);
driver.findElement(By.name("chk")).click();
driver.findElement(By.name("PROFILE_UPDATE")).click();
Alert alert = driver.switchTo().alert();
alert.accept();
driver.get("<logout url>");
int cellindex = 3;
WriteToFile.setExcelData(wb,filePath, sheetName, row.getRowNum(),cellindex, "PASS");
System.out.println("Inputted name: "+name+" and mailid: "+mailid);
Thread.sleep(2000);
}
else if(driver.findElements(By.name("loginForm")).size() == 0){
driver.findElement(By.name("loginForm")).isDisplayed();
System.out.println("Inputted name: "+name+" and mailid: "+mailid + "does not exist");
int cellindex = 3;
WriteToFile.setExcelData(wb,filePath, sheetName, row.getRowNum(),cellindex, "Fail");
return;
}
}
catch(UnreachableBrowserException e){
System.out.println("Exception occured");
}
}
}
There could be different ways to handle it. What i would suggest is below one.
Add another Catch block to catch Exceptions in method runTest. Return aBoolenvalue as false in case of exceptions. Based on the return type, decide on how to proceed further in you For Loop. I Guess this should help you solve the problem. Please let me know in case of any queries.
Related
Please check the code suggest correction:
package com.framework;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class DataDriveFramework {
public void readExcel(String filePath, String fileName, String sheetName) throws IOException {
File file = new File(filePath+"\\"+fileName);
FileInputStream fis = new FileInputStream(file);
Workbook loginWorkbook=null;
String fileExtension=fileName.substring(fileName.indexOf("."));
if(fileExtension.equals(".xlsx"))
{
loginWorkbook=new XSSFWorkbook(fis);
}
else if(fileExtension.equals("xls"))
{
loginWorkbook=new HSSFWorkbook(fis);
}
Sheet loginSheet=loginWorkbook.getSheet(sheetName);
int rowCount=loginSheet.getLastRowNum()-loginSheet.getFirstRowNum();
for(int i=1;1<rowCount+1;i++)
{
Row row=loginSheet.getRow(i);
String username=row.getCell(0).getStringCellValue();
String password=row.getCell(0).getStringCellValue();
test(username,password);
}
}
public void test(String username, String password)
{
WebDriver driver=new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
String baseURL="https://accounts.google.com";
driver.get(baseURL);
driver.findElement(By.id("identifierId")).sendKeys(username);
driver.findElement(By.xpath("/html/body/div[1]/div[1]/div[2]/div/c-wiz/div/div[2]/div/div[2]/div/div[1]/div/div/button/span")).click();
driver.findElement(By.xpath("//*[#id=\"password\"]/div[1]/div/div[1]/input")).sendKeys(password);
driver.findElement(By.xpath("//*[#id=\"passwordNext\"]/div/button/span")).click();
driver.quit();
}
public static void main(String[] args)throws IOException {
DataDriveFramework readFile=new DataDriveFramework();
String filePath="C:\\Users\\Shefali\\eclipse-workspace\\DataDriveFramework\\TestExcelSheet\\";
readFile.readExcel(filePath, "DataDriven.xls", "Sheet1");
}
}
The code is to fetch the data from excel sheet and login automatically.But I am getting an error--
"Exception in thread "main" java.lang.NullPointerException: Cannot invoke "org.apache.poi.ss.usermodel.Workbook.getSheet(String)" because "loginWorkbook" is "null"
at com.framework.DataDriveFramework.readExcel(DataDriveFramework.java:31)
at com.framework.DataDriveFrame.main(DataDriveFrame.java:60)"
You missed a dot '.' in the below line in readExcel() method:
else if(fileExtension.equals("xls"))
it should be like:
else if(fileExtension.equals(".xls"))
I have tried with the below code having two classes once is Class1-TestData and Method1-excel(),
And another call to access the parameters Class2-AdminLoginAction and Method2-Admin_Login().
Here is the problem with I need to call the string parameters like UID and PWD as I marked in the Screenshot attached. But the script showed some error and was unable to access it. So, How can I solve this problem, Am I going to the right approach or any other way? Please do need full as soon as possible.
Script image for two classes
import java.io.IOException;
import java.util.Date;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.*;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
public class AdminLoginAction extends TestData{
WebDriver d;
Date currentdate = new Date();
String Screenshotdate = currentdate.toString().replace(" ", "-").replace(":", "-");
ExtentSparkReporter spark = new ExtentSparkReporter("ExtentReport.html");
ExtentReports extent = new ExtentReports();
#Test()
public void Admin_Login() throws InterruptedException, IOException {
TestData excel = new TestData();
extent.attachReporter(spark);
ExtentTest test = extent.createTest("Launch browswer and access the WeClean Login page");
test.log(Status.PASS, "Launch browser success...!!!");
test.pass("Verified launching browser");
System.setProperty("webdriver.chrome.driver", "D:\\backup\\selenium\\chromedriver.exe");
d = new ChromeDriver();
d.manage().window().maximize();
d.get(URL);
Utils.CaptureScreenshot(d, Screenshotdate + "_Login.png");
d.findElement(By.id("loginUser")).sendKeys(UID);
d.findElement(By.id("password")).sendKeys(PWD);
d.findElement(By.id("loginButton")).click();
Thread.sleep(5000);
Utils.CaptureScreenshot(d, Screenshotdate + "_HomePage.png");
test.log(Status.PASS, "Admin Logged in Successful");
test.pass("Verified Admin logged in");
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.Test;
public class TestData{
public void excel() throws IOException {
String filePath = System.getProperty("user.dir")+"\\Inputfiles";
File file = new File(filePath + "\\TestData.xlsx");
FileInputStream inputStream = new FileInputStream(file);
XSSFWorkbook wb=new XSSFWorkbook(inputStream);
XSSFSheet sheet=wb.getSheet("Admin_inputs");
XSSFRow row2=sheet.getRow(1);
XSSFCell cell=row2.getCell(0);
double UID= cell.getNumericCellValue();
XSSFCell cell2 = row2.getCell(1);
String PWD = cell2.getStringCellValue();
}
You can try like this:
public class TestData {
double UID;
String PWD;
public void excel() throws IOException {
String filePath = System.getProperty("user.dir") + "\\Inputfiles";
File file = new File(filePath + "\\TestData.xlsx");
FileInputStream inputStream = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
XSSFSheet sheet = wb.getSheet("Admin_inputs");
XSSFRow row2 = sheet.getRow(1);
XSSFCell cell = row2.getCell(0);
UID = cell.getNumericCellValue();
XSSFCell cell2 = row2.getCell(1);
PWD = cell2.getStringCellValue();
}
}
In Admin_Login() method, am just printing UID and PWD, change the code according to your requirement:
public class AdminLoginAction extends TestData {
#Test()
public void Admin_Login() throws InterruptedException, IOException {
// TestData excel = new TestData(); // you don't need to create this object because you are already inheriting `TestData` class.
excel(); // before using UID and PWD you have to call excel() method.
System.out.println(UID);
System.out.println(PWD);
}
}
I am trying to attach screenshot for failed testcases from my path to Extent Report but somehow i am not able to attach into it.
I have tried my possible solution but it fails .
I have used extent report version 3
here is mine full code in separate extenreport class :
package com.qa.ExtentReportListener;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.testng.IReporter;
import org.testng.IResultMap;
import org.testng.ISuite;
import org.testng.ISuiteResult;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.xml.XmlSuite;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import com.aventstack.extentreports.reporter.configuration.Theme;
import com.crm.qa.util.TestUtil;
public class ExtentTestNGIReporterListener implements IReporter {
private static final String OUTPUT_FOLDER = "test-output/";
private static final String FILE_NAME = "Extent.html";
private ExtentReports extent;
private ExtentTest test;
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
init();
for (ISuite suite : suites) {
Map<String, ISuiteResult> result = suite.getResults();
for (ISuiteResult r : result.values()) {
ITestContext context = r.getTestContext();
buildTestNodes(context.getFailedTests(), Status.FAIL);
buildTestNodes(context.getSkippedTests(), Status.SKIP);
buildTestNodes(context.getPassedTests(), Status.PASS);
}
}
for (String s : Reporter.getOutput()) {
extent.setTestRunnerOutput(s);
}
extent.flush();
}
private void init() {
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(OUTPUT_FOLDER + FILE_NAME);
htmlReporter.config().setDocumentTitle("ExtentReports - Created by TestNG Listener");
htmlReporter.config().setReportName("ExtentReports - Created by TestNG Listener");
htmlReporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
htmlReporter.config().setTheme(Theme.STANDARD);
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
extent.setReportUsesManualConfiguration(true);
}
private void buildTestNodes(IResultMap tests, Status status) {
if (tests.size() > 0) {
for (ITestResult result : tests.getAllResults()) {
test = extent.createTest(result.getMethod().getMethodName());
for (String group : result.getMethod().getGroups())
test.assignCategory(group);
if (result.getThrowable() != null) {
test.log(status, result.getThrowable());
}
else {
test.log(status, "Test " + status.toString().toLowerCase() + "ed");
}
test.getModel().setStartTime(getTime(result.getStartMillis()));
test.getModel().setEndTime(getTime(result.getEndMillis()));
}
}
}
public void down(ITestResult result) throws IOException{
if(result.getStatus()==ITestResult.FAILURE){
test.log(Status.FAIL, "TEST CASE FAILED IS "+result.getName()); //to add name in extent report
test.log(Status.FAIL, "TEST CASE FAILED IS "+result.getThrowable()); //to add error/exception in extent report
String screenshotPath = TestUtil.takeScreenshotAtEndOfTest();
test.fail("Test Case failed check screenshot below"+test.addScreenCaptureFromPath(screenshotPath));
//extentTest.log(Status.FAIL, MediaEntityBuilder.createScreenCaptureFromPath(screenshotPath).build()); //to add screenshot in extent report
//extentTest.fail("details").addScreenCaptureFromPath(screenshotPath);
}
else if(result.getStatus()==ITestResult.SKIP){
test.log(Status.SKIP, "Test Case SKIPPED IS " + result.getName());
}
else if(result.getStatus()==ITestResult.SUCCESS){
test.log(Status.PASS, "Test Case PASSED IS " + result.getName());
}
extent.flush();
}
private Date getTime(long millis) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millis);
return calendar.getTime();
}
}
here is my util class which contain screenshot method:
public static String takeScreenshotAtEndOfTest() throws IOException {
String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
TakesScreenshot ts = (TakesScreenshot)driver;
File source = ts.getScreenshotAs(OutputType.FILE);
String destination = System.getProperty("user.dir") + "/screenshots/" + dateName
+ ".png";
File finalDestination = new File(destination);
FileHandler.copy(source, finalDestination);
return destination;
}
If you want take screen shots for failed test cases with test class name use below code segment.
Extent Report already provide the utility to take the screenshot .Please refer the below link:
https://extentreports.com/docs/versions/3/java/#automatic-screenshot-management
also find the snapshot and code for same:
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter("extent.html");
htmlReporter.config().setAutoCreateRelativePathMedia(true);
test1.fail("details", MediaEntityBuilder.createScreenCaptureFromPath("1.png").build());
test2.fail("details", MediaEntityBuilder.createScreenCaptureFromPath("2.png").build());
how to take Screenshot using extent report
Try using this :
logger.log(Status.FAIL, logger.addScreenCaptureFromPath("YOUR PATH"));
UPDATE :
If this doesn't work, just cast the inner logger with markup.
import com.aventstack.extentreports.markuputils.Markup;
package com.helper;
import org.testng.annotations.Test;
import com.aventstack.extentreports.AnalysisStrategy;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.MediaEntityBuilder;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.opera.OperaDriver;
import org.testng.IResultMap;
import org.testng.ITest;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
public class TestingEdgeDriver {
ExtentReports extent;
ExtentTest test;
WebDriver driver;
ExtentTest Parent;
ExtentTest child1,child;
#BeforeMethod
public void setup(){
DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH-mm-ss");
String destDir = dateFormat.format(new Date());
ExtentSparkReporter esp=new ExtentSparkReporter(System.getProperty("user.dir")+"/ExtentReport/ExtentReports_"+destDir+"/SwarupExtentReport.html");
extent=new ExtentReports();
extent.attachReporter(esp);
extent.setAnalysisStrategy(AnalysisStrategy.SUITE);
}
#Test (testName="Chrome browser Testing")public void chromeBrowser() throws IOException{
/*extent.attachReporter(spark);
extent.createTest("chromeBrowser").log(Status.PASS , "This is logging event for the setup and it is passed");
extent.flush();*/
Parent=extent.createTest("CMO");
child1=Parent.createNode("Test1");
child=child1.createNode("Chrome browser Testing");
System.out.println("The tread value for Chrome browser is "+ Thread.currentThread().getId());
System.setProperty("webdriver.chrome.driver","E:\\chromedriver_win32 (2)\\chromedriver.exe");
driver=new ChromeDriver();
child.log(Status.PASS, "Chrome browser has opened",MediaEntityBuilder.createScreenCaptureFromPath(capture(driver)).build());
driver.get("https://www.icicibank.com");
child.log(Status.PASS,"Expected was its should open the bank website",MediaEntityBuilder.createScreenCaptureFromPath(capture(driver)).build());
child.log(Status.PASS, "Need to open the URL "+" http://www.icicibank.com");
driver.manage().window().maximize();
child.log(Status.PASS, "Test Case is passed",MediaEntityBuilder.createScreenCaptureFromPath(capture(driver)).build());
}
#AfterMethod
public void getResult(ITestResult result){
if(result.getStatus()==ITestResult.SUCCESS){
child.log(Status.PASS, "Test case is passed "+result.getStatus()+" "+result.getTestClass()+" "+result.getName());
child.log(Status.PASS, "Test case is passed "+result.getTestName());
}
if(result.getStatus()==ITestResult.FAILURE){
child.log(Status.FAIL, "Test case is failed at below location "+result.getThrowable());
}
extent.flush();
}
/*#Test public void operaTesting(){
System.out.println("The tread value for Opera browser is "+ Thread.currentThread().getId());
System.setProperty("webdriver.opera.driver","E:\\operadriver_win32\\operadriver_win32\\operadriver.exe");
Reporter.log("opera driver has been set",true);
driver=new OperaDriver();
driver.manage().window().maximize();
driver.get("https://www.irctc.co.in");
}
#Test public void FirefoxTesting(){
System.out.println("The tread value for Firefox browser is "+ Thread.currentThread().getId());
System.setProperty("webdriver.gecko.driver","E:\\gecodriver\\geckodriver-v0.29.0-win32\\geckodriver.exe");
Reporter.log("Gecko Driver has been set",true);
driver=new FirefoxDriver();
driver.manage().window().maximize();
Reporter.log("firefox driver has been initialsed",true);
driver.get("https://www.primevideo.com/");
}
#Test public void InternetExplorerTesting(){
System.out.println("The tread value for IE browser is "+ Thread.currentThread().getId());
System.setProperty("webdriver.ie.driver","E:\\IEDriverServer_Win32_3.4.0\\IEDriverServer.exe");
Reporter.log("IE driver has been set",true);
driver=new InternetExplorerDriver();
driver.manage().window().maximize();
driver.get("https://www.hotstar.com/in");
}*/
public static String captureBase64(WebDriver driver) throws IOException {
String encodedBase64 = null;
FileInputStream fileInputStream = null;
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
File Dest = new File("src/../BStackImages/" + System.currentTimeMillis()
+ ".png");
String errflpath = Dest.getAbsolutePath();
FileUtils.copyFile(scrFile, Dest);
try {
fileInputStream =new FileInputStream(Dest);
byte[] bytes =new byte[(int)Dest.length()];
fileInputStream.read(bytes);
encodedBase64 = new String(Base64.encodeBase64(bytes));
}catch (FileNotFoundException e){
e.printStackTrace();
}
return "data:image/png;base64,"+encodedBase64;
}
public static String capture(WebDriver driver) throws IOException {
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
File Dest = new File("src/../BStackImages/" + System.currentTimeMillis()
+ ".png");
String errflpath = Dest.getAbsolutePath();
FileUtils.copyFile(scrFile, Dest);
return errflpath;
}
}
Use this code in after method
if(result.getStatus()==result.FAILURE || result.getStatus()==result.SKIP) {
String screenshotPath = util.captureScreenshot(driver, result.getName());
result.setAttribute("screenshotPath", screenshotPath); //sets the value the variable/attribute screenshotPath as the path of the sceenshot
}
and add below code in buildtestnodes
if(result.getStatus()==result.FAILURE || result.getStatus()==result.SKIP) {
String screenshotPath=(String)
result.getAttribute("screenshotPath");
test.log(status, test.addScreenCapture(screenshotPath));
}
Use this following example is in Java
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
// Store the screenshot in current project dir.
String screenShot = System.getProperty("user.dir")+"\\Artifacts\\FileName.png";
// Call Webdriver to click the screenshot.
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// Save the screenshot.
FileUtils.copyFile(scrFile, new File(screenShot));
I have used the following code (Reference link) to read data from an Excel file and using the data in two cells to search the Google site. However, when the program is run, data from two rows are placed in the searchbox together, not one after another in separate iteration as I'm expecting it by using the For loop. Looking forward to help. Here is the code:
package readdatafile;
import java.io.*;
import java.util.concurrent.TimeUnit;
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.openqa.selenium.firefox.FirefoxDriver;
public class DataDrivenUsingExcelFile {
String reafilefrom = "I:\\2000 QA\\Testing Tools\\Selenium\\Examples\\TestData\\testdata.xlsx";
public static void main(String[] args) throws IOException {
DataDrivenUsingExcelFile obj1 = new DataDrivenUsingExcelFile();
System.setProperty("webdriver.chrome.driver", "C://ChromeDriverForSelenium/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
driver.manage().window().maximize();
WebElement searchBox = driver.findElement(By.name("q"));
try{
FileInputStream file = new FileInputStream(new File(obj1.reafilefrom));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
for (int i=1; i<= sheet.getLastRowNum(); i++){
String keyword = sheet.getRow(i).getCell(0).getStringCellValue();
searchBox.sendKeys(keyword);
searchBox.submit();
driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
}
workbook.close();
file.close();
} catch (FileNotFoundException fnfe){
fnfe.printStackTrace();
}
// Waiting a little bit
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.close();
driver.quit();
}
}
Test data screenshot is below:
Thank you.
For every iteration in the for loop, you need to clear the searchtext input field before entering the new search string. Try the below code
for (int i=1; i<= sheet.getLastRowNum(); i++){
String keyword = sheet.getRow(i).getCell(0).getStringCellValue();
searchBox.clear();
searchBox.sendKeys(keyword);
searchBox.submit();
driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
}
Working on Selenium Webdriver and using Java. I'm getting error as The system cannot find the path specified
Code:
package test;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
public class OEPR_DefaultTab{
private static Logger Log = Logger.getLogger(OEPR_DefaultTab.class.getName());
private WebDriver driver;
private StringBuffer verificationErrors = new StringBuffer();
Properties p= new Properties();
public Selenium selenium;
#BeforeTest
public void Login() throws Exception {
driver = new FirefoxDriver();
try {
p.load(new FileInputStream("C:/Login.txt"));
} catch (Exception e) {
e.getMessage();
}
String url=p.getProperty("url");
DOMConfigurator.configure("src/log4j.xml");
Log.info("______________________________________________________________");
Log.info("Initializing Selenium...");
selenium = new DefaultSelenium("localhost", 4444, "*firefox",url);
Thread.sleep(5000);
Log.info("Selenium instance started");
try {
p.load(new FileInputStream("C:/Login.txt"));
} catch (Exception e) {
e.getMessage();
}
Log.info("Accessing Stored uid,pwd from the stored text file");
String uid=p.getProperty("loginUsername");
String pwd=p.getProperty("loginPassword");
Log.info("Retrieved uid pwd from the text file");
try
{
driver.get("https://10.4.16.159/login");
}
catch(Exception e)
{
Reporter.log("network server is slow..check internet connection");
Log.info("Unable to open the website");
throw new Error("network server is slow..check internet connection");
}
performLogin(uid,pwd);
}
public void performLogin(String uid,String pwd) throws Exception
{
Log.info("Sign in to the OneReports website");
Thread.sleep(5000);
Log.info("Enter Username");
driver.findElement(By.id("loginUsername")).sendKeys(uid);
Log.info("Enter Password");
driver.findElement(By.id("loginPassword")).sendKeys(pwd);
//submit
Log.info("Submitting login details");
waitforElement(driver,120 , "//*[#id='submit']");
driver.findElement(By.id("submit")).submit();
Thread.sleep(6000);
Actions actions = new Actions(driver);
Log.info("Clicking on Reports link");
if(existsElement("reports")==true){
WebElement menuHoverLink = driver.findElement(By.id("reports"));
actions.moveToElement(menuHoverLink).perform();
Thread.sleep(6000);
}
else{
Log.info("element not present");
System.out.println("element not present -- so it entered the else loop");
}
Log.info("Clicking on Extranet link");
if(existsElement("extranet")==true){
WebElement menuHoverLink = driver.findElement(By.id("extranet"));
actions.moveToElement(menuHoverLink).perform();
Thread.sleep(6000);
}
else{
Log.info("element not present");
System.out.println("element not present -- so it entered the else loop");
}
Log.info("Clicking on PR link");
if(existsElement("ext-pr")==true){
WebElement menuHoverLink = driver.findElement(By.id("ext-pr"));
actions.moveToElement(menuHoverLink).perform();
Thread.sleep(6000);
}
else{
Log.info("element not present");
System.out.println("element not present -- so it entered the else loop");
}
Log.info("Clicking on Overview and Evolution PR link");
if(existsElement("ext-pr-backlog-evolution")==true){
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", driver.findElement(By.id("ext-pr-backlog-evolution") ));
//executor.executeScript("document.getElementById('ext-pr-backlog-evolution').style.display='block';");
//driver.findElement(By.id("ext-pr-backlog-evolution")).click();
// WebElement menuHoverLink = driver.findElement(By.id("ext-pr-backlog-evolution"));
//actions.moveToElement(menuHoverLink).perform();
Thread.sleep(6000);
}
else{
Log.info("element not present");
System.out.println("element not present -- so it entered the else loop");
}
}
//Filter selection-1
#Test()
public void Filterselection_1() throws Exception{
BufferedReader in = new BufferedReader(new FileReader("C:/FilerSection/visualization.txt"));\\ Here i'm getting error
String line;
line = in.readLine();
in.close();
String[] expectedDropDownItemsInArray = line.split("=")[1].split(",");
// Create expected list :: This will contain expected drop-down values
ArrayList<String> expectedDropDownItems = new ArrayList<String>();
for(int i=0; i<expectedDropDownItemsInArray.length; i++)
expectedDropDownItems.add(expectedDropDownItemsInArray[i]);
// Create a webelement for the drop-down
WebElement visualizationDropDownElement = driver.findElement(By.id("visualizationId"));
// Instantiate Select class with the drop-down webelement
Select visualizationDropDown = new Select(visualizationDropDownElement);
// Retrieve all drop-down values and store in actual list
List<WebElement> valuesUnderVisualizationDropDown = visualizationDropDown.getOptions();
ArrayList<String> actualDropDownItems = new ArrayList<String>();
for(WebElement value : valuesUnderVisualizationDropDown){
actualDropDownItems.add(value.getText());
}
// Compare expected and actual list
for (int i = 0; i < actualDropDownItems.size(); i++) {
if (!expectedDropDownItems.get(i).equals(actualDropDownItems.get(i)))
System.out.println("Drop-down values are NOT in correct order");
}
}
private boolean existsElement(String id) {
try {
driver.findElement(By.id(id));
} catch (Exception e) {
System.out.println("id is not present ");
return false;
}
return true;
}
private void waitforElement(WebDriver driver2, int i, String string) {
// TODO Auto-generated method stub
}
#AfterTest
public void tearDown() throws Exception {
Log.info("Stopping Selenium...");
Log.info("______________________________________________________________");
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
Assert.fail(verificationErrorString);
}
}
}
Please check the code give me some solution.
The scenario which is present in the How to compare the drop down options is matching with the UI options in Selenium WebDriver?
For this scenario I'm trying to script. Please check the link as well.
If that's the exact text you are seeing this typically isn't a code issue - it means you need to update your PATH environment variable with the directory where java was installed.
Replace
BufferedReader in = new BufferedReader(new FileReader("C:/FilerSection/visualization.txt"));
with
BufferedReader in = new BufferedReader(new FileReader("C:\\FilerSection\\visualization.txt"));
This should help.