testng: [Utils] [ERROR] [Error] org.testng.TestNGException: Data Provider public static java.lang.Object[][]

Hi All, I have written the code to login to LetsKodeIt website and tried to run the code in a node(Selenium GRID) machine by passing the input thru Excel Utility. But this same code is working when i run the code by connecting to a node on the same machine(Hub and Node registered on the same machine)

Can any of you guys please fix the code or help me to fix and execute and produce results.

TestNG Version 6.12 Selenium Standalone Server 3.5.3 ExcelData.xlsx Error Trace.txt

Please find the attached code files and error trace file.

package utilities;
public class ExcelConstants {
    
    public static final String URL = "https://letskodeit.teachable.com/";
    public static final String File_Path = "C:\\Users\\Bobby\\Desktop\\Temp\\";
    public static final String File_Name = "ExcelData.xlsx";

}

package utilities;

import java.io.FileInputStream;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtility {

    private static XSSFWorkbook ExcelWBook;
    private static XSSFSheet ExcelWSheet;

    /*
     * Set the File path, open Excel file
     * @params - Excel Path and Sheet Name
     */
    public static void setExcelFile(String path, String sheetName) throws Exception {
        try {
            // Open the Excel file
            FileInputStream ExcelFile = new FileInputStream(path);

            // Access the excel data sheet
            ExcelWBook = new XSSFWorkbook(ExcelFile);
            ExcelWSheet = ExcelWBook.getSheet(sheetName);
        } catch (Exception e) {
            throw (e);
        }
    }

    public static String[][] getTestData(String tableName) {
        String[][] testData = null;

        try {
            // Handle numbers and strings
            DataFormatter formatter = new DataFormatter();
            XSSFCell[] boundaryCells = findCells(tableName);
            XSSFCell startCell = boundaryCells[0];
            
            XSSFCell endCell = boundaryCells[1];
            
            int startRow = startCell.getRowIndex() + 1;
            int endRow = endCell.getRowIndex() - 1;
            int startCol = startCell.getColumnIndex() + 1;
            int endCol = endCell.getColumnIndex() - 1;

            testData = new String[endRow - startRow + 1][endCol - startCol + 1];

            for (int i=startRow; i<endRow+1; i++) {
                for (int j=startCol; j<endCol+1; j++) {
                    // testData[i-startRow][j-startCol] = ExcelWSheet.getRow(i).getCell(j).getStringCellValue();
                    Cell cell = ExcelWSheet.getRow(i).getCell(j);
                    testData[i - startRow][j - startCol] = formatter.formatCellValue(cell);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return testData;
    }

    public static XSSFCell[] findCells(String tableName) {
        DataFormatter formatter = new DataFormatter();
        String pos = "begin";
        XSSFCell[] cells = new XSSFCell[2];

        for (Row row : ExcelWSheet) {
            for (Cell cell : row) {
                // if (tableName.equals(cell.getStringCellValue())) {
                if (tableName.equals(formatter.formatCellValue(cell))) {
                    if (pos.equalsIgnoreCase("begin")) {
                        cells[0] = (XSSFCell) cell;
                        pos = "end";
                    } else {
                        cells[1] = (XSSFCell) cell;
                    }
                }
            }
        }
        return cells;
    }
}

package utilities;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

public class Screenshots {
	

	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();
	}

	public static String takeScreenShot(WebDriver driver, String fileName) throws IOException {
		fileName = getRandomString(10) + ".png";
		
		//fileName = fileName + ".png";
		String directory = "C:\\Users\\Bobby\\Desktop\\Temp\\";

		File sourceFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
		FileUtils.copyFile(sourceFile, new File(directory + fileName));
		
		String destination = directory + fileName;
		return destination;
	}
}

package resource;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;

public class LetsKodeItPOM {
    WebDriver driver = null;
    ExtentTest test;
    
    public LetsKodeItPOM(WebDriver driver, ExtentTest test) {
        this.driver = driver;
        this.test = test;
    }
    public void LoginLink() throws Exception {
    	WebElement loginLink = driver.findElement(By.xpath("//a[contains(@href,'/sign_in')]"));
		loginLink.click();
		test.log(LogStatus.INFO, "Clicked On the Login Link...");
        Thread.sleep(2000);
    }
    public void EnterUsername(String emailid) throws Exception {
        WebElement userID = driver.findElement(By.id("user_email"));
        userID.sendKeys(emailid);
        test.log(LogStatus.INFO, "Entered User ID");
        Thread.sleep(2000);
    }
    
    public void EnterPassword(String password) throws Exception {
        WebElement userPassword = driver.findElement(By.id("user_password"));
        userPassword.sendKeys(password);
        test.log(LogStatus.INFO, "Entered User Password");
        Thread.sleep(2000);
    }
    
    public void LoginButton() throws Exception {
    	WebElement loginButton = driver.findElement(By.name("commit"));
		loginButton.click();
        test.log(LogStatus.INFO, "Clicked on the Login Button...");
        Thread.sleep(8000);
    }
     
   
    public boolean isProfilePicPresent() {
		WebElement profilePicIcon = null;
		try {
			profilePicIcon = driver.findElement(By.xpath("//div[@id='navbar']//a[@class='fedora-navbar-link navbar-link dropdown-toggle open-my-profile-dropdown']"));
			if (profilePicIcon != null) {
				return true;
			}
		}
		catch (NoSuchElementException e) {
			System.out.println(e.getMessage());
			return false;
		}
		return false;
	}
	
    public void ProfileAvatar() throws Exception {
    	WebElement profilePicIcon = driver.findElement(By.xpath("//div[@id='navbar']//a[@class='fedora-navbar-link navbar-link dropdown-toggle open-my-profile-dropdown']"));
    	profilePicIcon.click();
        test.log(LogStatus.INFO, "Clicked on the Profile Pic Tab...");
        Thread.sleep(2000);
    }
    
    public void LogoutButton() throws Exception {
    	WebElement logoutButton = driver.findElement(By.name("//div[@id='navbar']//li[@class='user-signout']"));
    	logoutButton.click();
        test.log(LogStatus.INFO, "Clicked on the Logout Button...");
        Thread.sleep(2000);
    }
    
    
	public void login(String emailid, String password) throws Exception {
		LoginLink();
		EnterUsername(emailid);
		EnterPassword(password);
		LoginButton();		
	}
	
	public void logout() throws Exception {
		ProfileAvatar();
		LogoutButton();
	}
}

package classes;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;

import resource.LetsKodeItPOM;
import utilities.ExcelConstants;
import utilities.ExcelUtility;
import utilities.Screenshots;

public class Selenium_Grid_Excel {

	protected WebDriver driver;
	String baseUrl;
	ExtentReports report;
	ExtentTest test;
	LetsKodeItPOM loginLKI;

	@Parameters({ "platform", "browser", "version", "url" })
	@BeforeClass(alwaysRun = true)
	public void setup(String platform, String browser, String version, String url)
			throws MalformedURLException, Exception {
		driver = getDriverInstance(platform, browser, version, url);

		test.log(LogStatus.INFO, "Browser Started...");
		loginLKI = new LetsKodeItPOM(driver, test);

		// Maximize the browser's window
		driver.manage().window().maximize();
		test.log(LogStatus.INFO, "Browser Maximized...");

		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		driver.get(ExcelConstants.URL);
		test.log(LogStatus.INFO, "Web Application Opened...");

		// Tell the code about the location of Excel file
		ExcelUtility.setExcelFile(ExcelConstants.File_Path + ExcelConstants.File_Name, "LoginTests");

	}

	public static WebDriver getDriverInstance(String platform, String browser, String version, String url)
			throws MalformedURLException {
		String nodeURL = "http://192.168.136.1:5555/wd/hub";
		WebDriver driver = null;
		DesiredCapabilities caps = new DesiredCapabilities();

		// Platforms
		if (platform.equalsIgnoreCase("Windows")) {
			caps.setPlatform(Platform.WINDOWS);
		}
		if (platform.equalsIgnoreCase("MAC")) {
			caps.setPlatform(Platform.MAC);
		}
		// Browsers
		if (browser.equalsIgnoreCase("chrome")) {
			caps = DesiredCapabilities.chrome();
			System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\Jars\\chromedriver_win32\\chromedriver.exe");
		}
		if (browser.equalsIgnoreCase("firefox")) {
			caps = DesiredCapabilities.firefox();
			System.setProperty("webdriver.gecko.driver",
					"C:\\Program Files\\Jars\\geckodriver-v0.19.0-win64\\geckodriver.exe");
		}
		// Version
		caps.setVersion(version);
		driver = new RemoteWebDriver(new URL(nodeURL), caps);

		// Open the Application
		driver.get(url);
		return driver;
	}

	@DataProvider(name = "loginData")
	public Object[][] dataProvider() {
		Object[][] testData = ExcelUtility.getTestData("Valid_Login");
		return testData;
	}

	@Test(dataProvider = "loginData")
	public void testLoginUsingExcel(String emailid, String password) throws Exception {

		loginLKI.login(emailid, password);

		// Thread.sleep(3000);

		boolean result = loginLKI.isProfilePicPresent();

		Assert.assertTrue(result);
		test.log(LogStatus.PASS, "Verified Avatar Profile Pic Icon for Successful Login...");

	}

	@AfterMethod
	public void sendScreenShot(ITestResult testResult) throws Exception {
		if (testResult.getStatus() == ITestResult.SUCCESS) {
			String path = Screenshots.takeScreenShot(driver, testResult.getName());
			String imagePath = test.addScreenCapture(path);
			test.log(LogStatus.PASS, "Verify Profile Pic Icon for Pass", imagePath);
		}

		else if (testResult.getStatus() == ITestResult.FAILURE) {
			String path = Screenshots.takeScreenShot(driver, testResult.getName());
			String imagePath = test.addScreenCapture(path);
			test.log(LogStatus.FAIL, "Couldn't verify Profile Pic Icon - Login Failed", imagePath);
		}
		loginLKI.logout();
	}

	@AfterClass
	public void cleanUp() throws Exception {

		// Thread.sleep(6000);
		driver.quit();
		test.log(LogStatus.INFO, "Closed/Quit Browser...");

		report.endTest(test);
		report.flush();

	}

}

Excel_Grid.xml:

<suite name="TestSuite">
<test name="FireFox Test">
<parameters>
<parameter name="platform" value="Windows"/>
<parameter name="browser" value="chrome"/>
<parameter name="version" value="60.0.3112.113"/>
<parameter name="url" value="https://letskodeit.teachable.com/"/>
</parameters>
<classes>
<class name="classes.Selenium_Grid_Excel">
</class>
</classes>
</test>
</suite>

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 21 (10 by maintainers)

Most upvoted comments

The problem is in your test code and has got nothing to do with TestNG.

  • In Selenium_Grid_Excel.setup() you are basically initializing your excel sheet logic using ExcelUtility.setExcelFile(ExcelConstants.File_Path + ExcelConstants.File_Name, "LoginTests");
  • But in your Selenium_Grid_Excel.dataProvider(), you are assuming that there will be a valid ExcelWSheet available. But in your case, it looks like ExcelWSheet is null and you cannot iterate over a null object.

You need to fix this in your code by starting here

java.lang.NullPointerException
	at utilities.ExcelUtility.findCells(ExcelUtility.java:70)
	at utilities.ExcelUtility.getTestData(ExcelUtility.java:40)
	at classes.Selenium_Grid_Excel.dataProvider(Selenium_Grid_Excel.java:92)

Hi Maha, Thanks for your reply.

I initialized the ExcelUtility.setExcelFile(ExcelConstants.File_Path + ExcelConstants.File_Name, “LoginTests”); inside my dataProvider() class and now it is working fine with node(different machine in the network) and Hub in the server. Now i am able to see the test running successfully in the node machine and got the results.

Once again, Thanks Mahadevan.