【问题标题】:Test write to file and read from file without parameters不带参数测试写入文件和读取文件
【发布时间】:2017-06-02 14:35:18
【问题描述】:

我想测试读取文件和写入文件功能。我的问题是函数没有任何参数。到目前为止,我只使用文件作为参数测试了这种功能。我查看了其他任务并找到了这些:How to unit test a method that reads a given fileHow to test write to file in Java?,但它们并没有真正帮助我。我要测试的代码是:

public void loadData()
    {
        try(BufferedReader br=new BufferedReader(new FileReader(super.fileName))){
            String line;
            while((line=br.readLine())!=null){
                String[] atributes=line.split(";");
                if(atributes.length!=4)
                    throw new Exception("Linia nu este valida!");
                Student t=new Student(atributes[0],atributes[1],atributes[2],atributes[3]);
                super.save(t);

            }
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public synchronized void writeToFile() {
        try (BufferedWriter br = new BufferedWriter(new FileWriter(super.fileName))){
            super.entities.forEach(x -> {
                try {
                    br.write(x.studentFileLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

谁能告诉我如何在没有文件参数的情况下进行测试?

【问题讨论】:

  • 您提到的帖子解释了一个重要的观点:使您的代码可测试。在无法设置文件参数的情况下对其进行测试不会使代码可测试。如果您想保持代码不可测试,您可能会找到一种依赖于不良做法的方法。
  • 如何分配super.fileName
  • 顺便说一句,“属性”中有一个双 't'。我只是指出这一点,因为它在这个来源中经常重复。
  • @slim 来源不是我。来自 AbstractFileRepository 的文件 si。
  • @user7167081 谁写的并不重要。我们需要知道它是如何设置的。据我们所知,超类中有一个 setFilename()getFilename() 可以解决您的问题。

标签: java junit bufferedreader bufferedwriter


【解决方案1】:

如果您无法更改现有方法的签名,则添加一个带有参数的新方法,并将现有方法更改为委托给新方法。

@Deprecated 
public void loadData() {
    loadData(super.fileName);
}

public void loadData(String fileName) {
    // do stuff
}

@Deprecated
public synchronized void writeToFile() {
    writeToFile(super.fileName);
}

public synchronized void writeToFile(String fileName) {
    // do stuff
}

【讨论】:

    猜你喜欢
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 2013-10-21
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多