testng-team / testng

TestNG testing framework
https://testng.org
Apache License 2.0
1.98k stars 1.02k forks source link

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

Closed rcrtwork closed 7 years ago

rcrtwork commented 7 years ago

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>

juherr commented 7 years ago

Not a TestNG issue. Please, post on stackoverflow instead.

krmahadevan commented 7 years ago

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

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)
rcrtwork commented 7 years ago

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.

Adminsa1 commented 6 years ago

Hi Mahadevan,

I am having same problem, could you post the screenshot of how you corrected yours.

krmahadevan commented 6 years ago

@Adminsa1 - I wasn't having the issue to begin with. I was only solving someone else's issue. You can start off by posting your query on the testng-users google groups

Somupatil commented 6 years ago

I am having the same problem ,org.testng.TestNGException
Please explain it properly bcz i m executing it by using supporting tool Maven and Frame work is Data driven

krmahadevan commented 6 years ago

@Somupatil,

You haven't shown us the test code, the exception nor have you told us what version are you working with.

Without any of this, what do you expect as explanations ?

I would instead recommend that you post your query on the testng-users Google forum including all of the details that I mentioned above.

We use GITHUB to typically track bugs or feature requests. In your case we are yet to even figure out if it's either of them. So the Google forum will be a good start.

--

Thanks & Regards Krishnan Mahadevan

"All the desirable things in life are either illegal, expensive, fattening or in love with someone else!" My Scribblings @ http://wakened-cognition.blogspot.com/

My Technical Scribbings @ http://rationaleemotions.wordpress.com/

Somupatil commented 6 years ago

Hi All, I have written the code for login Error.txt

These are the codes

Homepage

package com.test.automatiom.mfb.uIActios;       
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
import com.test.automation.mfb.testbase.TestBase;

public class HomePage extends TestBase {
    public static final Logger log = Logger.getLogger(HomePage.class.getName());
        WebDriver driver;

        @FindBy(id="login")
        WebElement Login;

        @FindBy(xpath="//*[@id='txtFullName']")
        WebElement Username; 

        @FindBy(xpath="//*[@id='txtPassword']")
        WebElement Password;

        @FindBy(xpath="//*[@id='sign_in']")
        WebElement Submit;

        public HomePage(WebDriver driver) {
            PageFactory.initElements(driver,this);  

        }

public void loginApplication(String emailaddress,String password){
    Login.click();
    log.info("Click on signin object is :"+Login.toString());
//  log.info("meassage from my number:"+Login.toString());
    Username.sendKeys(emailaddress);
    log.info("Enter Emailsddress :"+Username.toString());
    Password.sendKeys(password);
    log.info("Enter Password :"+Password.toString());
    Submit.click();
    log.info("Click on Submit :"+Submit.toString());
}
}

TestBase

package com.test.automation.mfb.testbase;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.openqa.selenium.JavascriptExecutor;
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.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Reporter;

import com.test.automation.excelReader.ExcelReader;

public class TestBase {
    public static final Logger log = Logger.getLogger(TestBase.class.getName());
    public WebDriver driver;
//  String Url = "https://www.myfundbucket.com/";
     String Url = "https://www.myfundbucket.com/";
//  String Browser = "firefox";
     String Browser ="chrome";
    public void init() {
        SelectBrowser(Browser);
        getUrl(Url);
    }
    public void SelectBrowser(String Browser) {
        if (Browser.equalsIgnoreCase("firefox")) {
            System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir") + "/driver/geckodriver.exe");
            log.info("creating the object of this browser" + Browser);
            driver = new FirefoxDriver();
        } else if (Browser.equalsIgnoreCase("chrome")) {
            System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "/driver/chromedriver.exe");
            log.info("creating the object of this browser" + Browser);
            driver = new ChromeDriver();
        }       
    }
    public void getUrl(String Url) {
        driver.get(Url);
        log.info("navigating to Url" + Url);
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);}
        public String[][] getdata(String sheetName, String excelName) {
            String path = System.getProperty("user.dir")+"src\\main\\java\\com\\test\\automation\\mfb\\data"+excelName;     
            ExcelReader excel = new ExcelReader(path);
            String[][] data = excel.getDataFromSheet(sheetName, excelName);
            return data;    
        }
    }

Test Class to run

package com.test.automation.mfb.homePage;

import org.apache.log4j.Logger;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import com.test.automatiom.mfb.uIActios.HomePage;
import com.test.automation.mfb.testbase.TestBase;

public class TC003_Login extends TestBase{
    public static final Logger log = Logger.getLogger(TC003_Login.class.getName());
    HomePage homepage;

    @DataProvider(name = "loginData")
    public String[][] getTestData() {
        String[][] testRecords = getdata("logindata", "Testdata.xlsx");
        return testRecords;

    }

    @BeforeTest
    public void setup() {       
        init();
    }

    @Test(dataProvider = "loginData")
    public void testLogin(String EmailAddress, String Password) {
        log.info("...starting verifying login for different cerdentials");
        homepage = new HomePage(driver);
        homepage.loginApplication(EmailAddress,Password);
        log.info("....finished verifying login for different credentials.....");
    }
}
krmahadevan commented 6 years ago

@Somupatil - As I mentioned before, you should be posting this as a question on the TestNG users google forum.

The problem is in your test code. Your @DataProvider annotated method must either return an Iterator<Object[]> (or) Object[][]. Your data provider is returning back a 2D String array.

juherr commented 6 years ago

@krmahadevan In fact, I think it should work with a 2D string array. And if not, the error message could be more explicit.

krmahadevan commented 6 years ago

@juherr - Yes you were right. It does work. My bad. Thanks for correcting me.

@Somupatil - You are working with TestNG 6.12.0. I would request you to please upgrade to the latest released version viz., 6.14.3 and try again. If its still a problem, please create a new issue, and attach a sample that can be used to reproduce the problem (Please keep the sample simple, and not include any reference to any other library. It would be great if you could just use core java to create the sample)

Lavanya23-design commented 4 years ago

hi, can you please tell me the how can i solve this error

org.testng.TestNGException: Some DataProvider public static void Utilities.Datadriven.main(java.lang.String[]) throws java.io.IOException parameters unresolved: at 0 type class [Ljava.lang.String;

krmahadevan commented 4 years ago

@Lavanya23-design - Please post this on the testng-users@googlegroups.com and include the following:

  1. TestNG version that you are using.
  2. What does your sample code look like (both your test method and your data provider)
  3. The complete stack trace of the error
  4. How are you running the tests ?
Lavanya23-design commented 4 years ago

Baseclass: System.out.println("browser opened successfully");

    String location = "C:\\Users\\Lavanya\\Documents\\jars\\geckodriver-v0.26.0-win64\\geckodriver.exe";
    System.setProperty("webdriver.gecko.driver", location);
    driver = new FirefoxDriver();

    Thread.sleep(2000);

    Robot rb = new Robot();
    rb.mouseMove(630, 420);
    rb.delay(1500);
    rb.mousePress(InputEvent.BUTTON1_DOWN_MASK);
    rb.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
    rb.delay(1500);
    rb.keyPress(KeyEvent.VK_DOWN);
    Thread.sleep(2000);
    rb.keyPress(KeyEvent.VK_ENTER);

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

    driver.get("https://qa.sourcelead.com/login");
    driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
Lavanya23-design commented 4 years ago

Datadriven: @DataProvider(name = "TestData") public static void main(String[] args) throws IOException {

FileInputStream fi = new FileInputStream("C:\\Users\\Lavanya\\workspace\\Learning\\TestData\\datadriven test.xlsx");

wb= new XSSFWorkbook(fi); sheet=wb.getSheet("Sheet1"); try {

for(int i=1; i<=sheet.getLastRowNum(); i++){ String name=sheet.getRow(i).getCell(0).getStringCellValue(); System.out.println(name);

String identity= sheet.getRow(i).getCell(1).getStringCellValue();
System.out.println(identity);
}
}catch(Exception e){
 e.getMessage();
}   

}

}

Lavanya23-design commented 4 years ago

Loginpage:

public class LoginPage {

WebDriver driver1;
static By sourceleaduserName = By.xpath("//input[@id='usernameval']");
static By sourceleadpassword = By.xpath("/html/body/div[3]/div[1]/div/form/span[2]/input");
static By submit = By.xpath("/html/body/div[3]/div[1]/div/form/input[7]");
//static By location=By.xpath("//div[@id='locDiv41782']");

public LoginPage(WebDriver driver)
{
this.driver1=driver;

}

public LoginPage() {

public void loginApplication(String username) { driver1.findElement(sourceleaduserName).sendKeys(username); } public void loginuser(String password) { driver1.findElement(sourceleadpassword).sendKeys(password); } public void clickLogin() { driver1.findElement(submit).click(); } public void loginintoSourcelead(String username,String password) { this.loginApplication(username); this.loginuser(password); this.clickLogin();

}
Lavanya23-design commented 4 years ago

Logintest: public class LoginTest extends Baseclass { public WebDriver driver1;

LoginPage lp= new LoginPage(driver1);
@Test(dataProvider="TestData",dataProviderClass=Datadriven.class)
public void Login(String username,String password)
{
    System.out.println("login test case program started");
    lp.loginintoSourcelead(username, password);
    System.out.println("program executed successfully");
}

}
Lavanya23-design commented 4 years ago

can u please give me the clarity where did i wrote the wrong code

Lavanya23-design commented 4 years ago

testNg version:6.11

krmahadevan commented 4 years ago

@Lavanya23-design - Please post your question on the TestNG forums : https://groups.google.com/forum/#!forum/testng-users

Note: The latest released version of TestNG is 7.1.0. Please use that.

krmahadevan commented 4 years ago

@NavdeepKSidhu - If you need help with anything on TestNG I would suggest that you please post your query on the testng-users google forums.

https://groups.google.com/g/testng-users