【问题标题】:Reading txt file in one Test case works but does not in another test case在一个测试用例中读取 txt 文件有效,但在另一个测试用例中无效
【发布时间】:2021-12-10 16:10:30
【问题描述】:

我是这里的 Java 新手。 在我的程序中,我正在执行一个 shell 脚本,将其导出到一个 txt 文件并提取该 txt 文件的部分内容并打印出来。

我的代码如下

public static void Shell(String picture){
try {
  File dir = new File("/usr/local/bin");
  ProcessBuilder pb = new ProcessBuilder(new String[]{"/bin/bash", "-c", "./javatest.sh"});
  pb.directory(dir);
  pb.redirectOutput(new File("/usr/local/bin/" + picture + ".txt"));
  Process start = pb.start();
  start.getOutputStream();
  pb.command("q\n");
  start.destroy();
  System.out.println("first line succeeded");

}catch (Exception e){
  e.printStackTrace();
  log.info("Error.Running.CMD");
}
try{
  String format = MessageFormat.format("/usr/local/bin/{0}.txt", picture);
  System.out.println("got file");
  String line17 = Files.readAllLines(Paths.get(format)).get(16);
  System.out.println("got line");
  String subStr = line17.substring(5);
  String line19 = Files.readAllLines(Paths.get("/usr/local/bin/" + picture +".txt")).get(18);

  String pattern = "\\: (.*)"; // Capture everything after ':' colon character
  String pattern2 = "(.*) \\:";

  Pattern r = Pattern.compile(pattern);
  Pattern r2 = Pattern.compile(pattern2);

  Matcher m = r.matcher(line19);
  Matcher m2 = r2.matcher(subStr);

  if (m.find( ) && m2.find( )) {
    System.out.println("Found value: " + m.group(1) );
    System.out.println(m2.group(1));
  }

}catch (IOException e) {
  System.out.println("entry not found.");
}

}

当我运行这个测试用例时,我确实得到了我想要的 txt 文件,但根据日志,正确读取 txt 文件似乎有问题。

但是,当我将第二个 try/catch 部分复制到单独的测试文件时,它似乎可以正常工作。

public static void checkPrint(String picture){
try{
  String format = MessageFormat.format("/usr/local/bin/{0}.txt", picture);
  String line17 = Files.readAllLines(Paths.get(format)).get(16);
  String subStr = line17.substring(5);
  String line19 = Files.readAllLines(Paths.get("/usr/local/bin/" + picture +".txt")).get(18);

  String pattern = "\\: (.*)"; // Capture everything after ':' colon character
  String pattern2 = "(.*) \\:";

  Pattern r = Pattern.compile(pattern);
  Pattern r2 = Pattern.compile(pattern2);

  Matcher m = r.matcher(line19);
  Matcher m2 = r2.matcher(subStr);

  if (m.find( ) && m2.find( )) {
    System.out.println("Found value: " + m.group(1) );
    System.out.println(m2.group(1));
  }

}catch (IOException e) {
  System.out.println("entry not found.");
}

}

我导入了相同的库,但我根本不明白为什么它可以在一个测试用例中工作,而不是在不同的测试文件中。

任何形式的反馈都将不胜感激。

提前谢谢你!

【问题讨论】:

    标签: java testing text error-handling


    【解决方案1】:

    找到了这个问题的答案。 该过程需要时间来创建 txt 文件。 我让线程休眠并且它起作用了!

    【讨论】:

    • 很高兴您找到了解决方案 Adam。但这不是解决这个问题的最佳方法!如果这个过程花费的时间超过你的睡眠时间怎么办?如果它需要的更少呢?然后你在这两种情况下浪费时间或引发异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多