从CSV读取输入以使用Java和Selenium在Web表单中创建多个条目

时间:2017-12-01 11:53:21

标签: java csv selenium automated-tests

所以我尝试使用Java Selenium在Web表单中创建5个不同的条目。

使用下面的代码,它是从CSV读取并输入第一个条目但是然后只添加相同的数据5次,而不是csv中的5个不同的条目,我无法弄清楚我哪里出错?< / p>

@Then("^I can make multiple bookings$")
public void i_can_make_multiple_bookings() throws Throwable {
    String csvFile = "hotelsDatas.csv";
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";

    try {
        br = new BufferedReader(new FileReader(csvFile));

        while ((line = br.readLine()) != null) {
            // Use comma as separator
            String[] hotels = line.split(cvsSplitBy);
            // Reading a line column by column
            for (int i = 0; i < hotels.length; i++) {
                System.out.print(hotels[i].replaceAll("\"", ""));

                driver.findElement(By.id("firstName")).sendKeys(hotels[0].replaceAll("\"", ""));
                driver.findElement(By.id("lastName")).sendKeys(hotels[1].replaceAll("\"", ""));
                driver.findElement(By.id("totalPrice")).sendKeys(hotels[2].replaceAll("\"", ""));
                driver.findElement(By.id("depositPaid")).sendKeys(hotels[3].replaceAll("\"", ""));
                driver.findElement(By.id("checkIn")).sendKeys(hotels[4].replaceAll("\"", ""));
                driver.findElement(By.id("checkOut")).sendKeys(hotels[5].replaceAll("\"", ""));

                driver.findElement(By.id("createBooking")).click();
            }

            System.out.println(); // next line
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

为什么不首先将您的CSV文件作为List<Map>阅读并从那里开始工作?

之后,您可以遍历List和每个Map,对每个 Key - Value 对执行操作。

import java.io.*;
import java.lang.reflect.Type;
import java.util.*;
import java.util.stream.Collectors;

import com.opencsv.CSVReader;

public class Reader {
    public static List<Map<String, Object>> readCsv(String filename) throws IOException {
        return readCsv(filename, null, null);
    }

    public static List<Map<String, Object>> readCsv(String filename, String[] headers) throws IOException {
        return readCsv(filename, headers, null);
    }

    public static List<Map<String, Object>> readCsv(String filename, Type[] types) throws IOException {
        return readCsv(filename, null, types);
    }

    public static List<Map<String, Object>> readCsv(String filename, String[] headers, Type[] types) throws IOException {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        InputStream is = Reader.class.getClassLoader().getResourceAsStream(filename);
        InputStreamReader reader = new InputStreamReader(is);
        CSVReader csv = new CSVReader(reader);

        if (headers == null) {
            headers = csv.readNext();
        }

        String[] row;
        while ((row = csv.readNext()) != null) {
            Map<String, Object> entry = new HashMap<String, Object>();

            for (int i = 0; i < row.length; i++) {
                String value = row[i];

                if (types != null) {
                    if (types[i] == Double.class) {
                        entry.put(headers[i], Double.parseDouble(value));
                    } else if (types[i] == Date.class) {
                        entry.put(headers[i], new Date(Long.parseLong(value)));
                    } else if (types[i] == Boolean.class) {
                        entry.put(headers[i], new Boolean(value.toLowerCase().equals("true") || value.toLowerCase().equals("yes")));
                    } else {
                        entry.put(headers[i], value);
                    }
                }
            }

            result.add(entry);
        }

        csv.close();
        reader.close();
        is.close();

        return result;
    }

    public static void main(String[] args) {
        try {
            Type[] types = { String.class, String.class, Double.class, Boolean.class, Date.class, Date.class };
            List<Map<String, Object>> records = readCsv("data.csv", types);

            System.out.println(records.stream().map(Object::toString).collect(Collectors.joining(System.lineSeparator())));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

输入

firstName,lastName,totalPrice,depositPaid,checkIn,checkOut
Jane,Doe,200.00,yes,1512129600000,1512331200000
John,Smith,350.00,no,1512720000000,1512925200000

输出

{firstName=Jane, lastName=Doe, checkIn=Fri Dec 01 07:00:00 EST 2017, totalPrice=200.0, checkOut=Sun Dec 03 15:00:00 EST 2017, depositPaid=true}
{firstName=John, lastName=Smith, checkIn=Fri Dec 08 03:00:00 EST 2017, totalPrice=350.0, checkOut=Sun Dec 10 12:00:00 EST 2017, depositPaid=false}

依赖关系

<强>摇篮

compile 'com.opencsv:opencsv:4.1'

Maven

<dependency>
  <groupId>com.opencsv</groupId>
  <artifactId>opencsv</artifactId>
  <version>4.1</version>
  <type>pom</type>
</dependency>

直接下载

  

>> opencsv-4.1jar

答案 1 :(得分:0)

下面的代码会给您带来麻烦:

member1=parcel.readString()
member2=parcel.readInt()

让我们假设csv文件中的数据如下所示: String[] hotels = line.split(cvsSplitBy); // Reading a line column by column for (int i = 0; i < hotels.length; i++) { System.out.print(hotels[i].replaceAll("\"", "")); driver.findElement(By.id("firstName")).sendKeys(hotels[0].replaceAll("\"", "")); driver.findElement(By.id("lastName")).sendKeys(hotels[1].replaceAll("\"", "")); driver.findElement(By.id("totalPrice")).sendKeys(hotels[2].replaceAll("\"", "")); driver.findElement(By.id("depositPaid")).sendKeys(hotels[3].replaceAll("\"", "")); driver.findElement(By.id("checkIn")).sendKeys(hotels[4].replaceAll("\"", "")); driver.findElement(By.id("checkOut")).sendKeys(hotels[5].replaceAll("\"", "")); driver.findElement(By.id("createBooking")).click(); }

您使用"one","two","three","four","five","six","seven","eight","nine","ten"拆分数据,并使用,创建String[]的实例 这意味着您的String[] hotels = line.split(cvsSplitBy);数组如下所示:

hotels[](我使用了String转义符,因为我可以看到,您正在hotels[0] = "\"one\"";循环中替换代码中的"

for

现在看一下hotels[1] = "\"two\""; hotels[2] = "\"three\""; hotels[3] = "\"four\""; hotels[4] = "\"five\""; hotels[5] = "\"six\""; hotels[6] = "\"seven\""; hotels[7] = "\"eight\""; hotels[8] = "\"nine\""; hotels[9] = "\"ten\""; 循环 for

由于for (int i = 0; i < hotels.length; i++)为您提供了10个元素,hotels.length循环将执行10次。

现在看看每次迭代:

for

i=0 将在控制台中打印System.out.println

驱动程序将在one中输入one 司机将在firstName中输入two 司机将在lastName中输入three

然后点击totalPrice元素。

它只是第一次迭代。

当我们进行迭代createBooking时,系统将打印i=1。但由于two的代码位于driver.findElement循环中,因此它将在相同的字段中输入相同的数据。并且它将继续完成,直到迭代结束。

你应该摆脱for循环。你不需要它。