简体   繁体   中英

How can I get my data from csv file to DataProvider

I need to take data(username and password) from my csv.file and use it to register some new Users using DataProvider in Selenium. I have made already Reader to read this file but i can not put this data in DataProvider correctly. Help me please.

I created a method for reading csv file and test with provider for working.

my method public static List users = new ArrayList<>();

public static Object openCSVReader() throws IOException {

    CSVReader reader = new CSVReader(new FileReader(System.getProperty("user.dir") + "\\src\\test\\resources\\users.csv"), ',');

    // read line by line
    String[] record = null;

    while ((record = reader.readNext()) != null) {
        User user = new User("username", "password");
        user.setUsername(record[0]);
        user.setPassword(record[1]);
        users.add(user);
    }


    reader.close();
    return users;

}

my test

@Test(dataProvider = "registration")
    public void registerCSVFiles(String username, String password) throws IOException {
        registerPage.writeInForm(user);
        registerPage.writeFile(user);
        registerPage.selectUserAndRegister();
    }
}
    @DataProvider(name = "registration")
    public static Object[][] credentials() throws IOException {
        return new Object[][]{
                {users.get(0)},{users.get(1)}
        };
    }

I can not take data from my openCSVReader. Help pls

May be following approach can be useful to fulfill your requirement.

sample content of csv file is as below. (users.csv)

user1,password1

user2,password2

Test class is composed as below;

@DataProvider(name = "userDetails")
public static Object[][] readCsv() throws IOException {
    CSVReader csvReader = new CSVReader(new FileReader(System.getProperty("user.dir")+"/src/test/resources/users.csv"),',');
    List<String[]> csvData=csvReader.readAll();
    Object[][] csvDataObject=new Object[csvData.size()][2];
    for (int i=0;i<csvData.size();i++) {
        csvDataObject[i]=csvData.get(i);
    }
    return  csvDataObject;
}

@Test(dataProvider = "userDetails")
public void userLoginTest(String userName,String password){
    System.out.println(userName+" "+password);
}

Note: DataProvider method should reside in the same class where test method exist or it should resides its base class

Used libraries : OpenCSV

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM