java - 读取文件 - 哪种方法是可测试的?

标签 java file

在下面的问题中,我必须读取文本文件并进行一些“处理”。教程中有很多读取文件的方法。但是,我想测试我的代码,甚至不先读取文件。相反,我想读取带有某个类的文件,该类具有实用程序方法来将行注入(inject)其中,而不是实际从文件中读取它们。哪种文件读取方法可以让我做到这一点?

我需要的伪代码:

TestableFileReader.injectLine("1.0, 2.0, 3.0, -1100");//Garbage data in line.
String line = TestableFileReader.readNextLine();
doProcessing(line);

Write a method public ArrayList readValues(String filename) throws ... that reads a file containing floating-point numbers. Throw appropriate exceptions if the file could not be opened or if some of the inputs are not floating-point numbers.

最佳答案

这是执行此操作的代码。可以重构代码,以便轻松地使用字符串行的各种值进行自动化测试,而不是硬编码固定字符串,如下所示。

//Method signature from book.
public static List<Double> readValues(String filename) throws IOException {
    ArrayList<Double> values = new ArrayList<>();
    String line = "1.0, 2.5, 3, -5, A, ë";
    Reader reader = new StringReader(line); //new FileReader(filename);

    //Is there a shorter way to do this, i.e without try-catch ?
    Function<String, Boolean> isStringDouble = (string -> {
        try{
            return Double.valueOf(string) instanceof Double;
        }catch (NumberFormatException ex){
            return false;
        }
    });


    //Decorate reader with BufferedReader to get readLine functionality.
    try(BufferedReader bReader = new BufferedReader(reader)){
        while ((line = bReader.readLine()) != null) {
             Map<Boolean, List<String>> lineParts = Arrays
                     .stream(line.split(","))
                     .map(v -> v.trim())
                     .collect( Collectors.groupingBy(v -> isStringDouble.apply(v)) );

             lineParts.forEach( ( (k, v) -> System.out.printf("are doubles = %s : %s\n", k, v)  ) );
        }
    }
    return values;
}

public static void main(String [] args) throws Exception {
    readValues("hello");
}

关于java - 读取文件 - 哪种方法是可测试的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60610678/

相关文章:

python - 检查对象是否在 Python 中类似于文件

php - 使用codeigniter上传文件时出错

java - HashedWheelTimer vs ScheduledThreadPoolExecutor 以获得更高的性能

java - 具有存储库工厂的存储库模式

java - Appium 测试中的 SessionNotCreatedException 错误

java - 从 Intent 获取上下文

file - 将特定行从一个文件复制到另一个文件的 unix 命令是什么?

java - Java Sound API播放音频文件后将其锁定

asp.net-mvc - ASP.NET MVC 中的四个文件结果有什么区别

ruby-on-rails - Ruby on Rails PaperClip - 如何将文件存储在 S3 或公共(public)文件夹以外的其他位置