使用.txt文件中的行作为测试中的数据

时间:2015-10-14 14:16:50

标签: java selenium selenium-webdriver

对于我们团队正在构建的框架,我们需要制作一个文本文件,我们将在运行测试之前对其进行编辑。该文本文件有两行 - 我们的Web应用程序的URL,以及包含测试用例的excel文件的位置。

目前,为了阅读该文件,我一直在使用Scanner

 private static void readFile(String fileName) {
   try {
     File file = new File(fileName);
     Scanner scanner = new Scanner(file);
     while (scanner.hasNextLine()) {
       System.out.println(scanner.nextLine());
     }
     scanner.close();
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   }
 }

我的代码术语不是最好的,所以试着得到我的要求:

有人能指出我从文本文件中提取这两行(URL和Excel路径)的正确方向,将它们分配给两个不同的变量/对象/函数/无论你真正想要调用它们,还是将它们传递给主测试脚本,以便测试脚本知道它想要做什么。

我画了一幅画。花了100个小时。

100 hours in paint

2 个答案:

答案 0 :(得分:1)

private String urlText;
private String excelLocation;

private static void readFile(String fileName) {
   try {
     int lineNumber = 0;
     File file = new File(fileName);
     Scanner scanner = new Scanner(file);
     while (scanner.hasNextLine()) {
       lineNumber++;
       if (lineNumber == 1){
       urlText = scanner.nextLine();
       }
       else{
       excelLocation = scanner.nextLine();
     }
     scanner.close();
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   }
 }

如果你想要更详细,你也可以使用LineNumberReader。见这里:How to get line number using scanner

答案 1 :(得分:1)

您可以使用Properties对象

写入文件:

Properties prop = new Properties();
OutputStream output = null;

try {

    output = new FileOutputStream("yourfile.txt");

    // set the properties value
    prop.setProperty("database", "localhost");
    prop.setProperty("dbuser", "john");
    prop.setProperty("dbpassword", "password");

    // save properties to project root folder
    prop.store(output, null);

} catch (IOException io) {
    io.printStackTrace();
} finally {
    if (output != null) {
        try {
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

阅读:

Properties prop = new Properties();
InputStream input = null;

try {

    input = new FileInputStream("yourfile.txt");

    // load a properties file
    prop.load(input);

    // get the property value and print it out
    System.out.println(prop.getProperty("database"));
    System.out.println(prop.getProperty("dbuser"));
    System.out.println(prop.getProperty("dbpassword"));

} catch (IOException ex) {
    ex.printStackTrace();
} finally {
    if (input != null) {
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

您将获得一个带有以下行的“yourfile.txt”文件:

dbpassword=password
database=localhost
dbuser=john

我从以下代码中获取了代码:http://www.mkyong.com/java/java-properties-file-examples/