0

I want to test a read from file and a write to file functions. My problem is that the functions don;t have any parameters. Until now i've tested this kind of fucntions only with the file as parameter. I've looked through other questins and found these: How to unit test a method that reads a given file, How to test write to file in Java? but they didn't really help me. The code i want ot test is:

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();
        }
    }

Can anybody give me a hint about how to test this without the file parameter?

user7167081
  • 39
  • 1
  • 1
  • 8
  • 1
    The posts you refer explain an important point : making your code testable. Testing it without being able to set the file parameter doesn't make the code testable. If you want to keep a code not testable, you will probably get a way relying on bad practices. – davidxxx Jun 02 '17 at 14:37
  • How does `super.fileName` get assigned? – slim Jun 02 '17 at 15:12
  • BTW there is a double 't' in "attributes". I only point this out because it's repeated so often in this source. – slim Jun 02 '17 at 15:14
  • @slim It's not me who made the source. The file si from an AbstractFileRepository. – user7167081 Jun 02 '17 at 15:28
  • @user7167081 it doesn't matter who wrote it. We need to know how it gets set. For all we know there's a `setFilename()` or a `getFilename()` in the superclass that would solve your problem. – slim Jun 02 '17 at 15:34

1 Answers1

0

If you cannot change the signature of the existing method then add a new method which does take a parameter, and change the existing method to delegate to the new method.

@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
}
Andrew S
  • 2,509
  • 1
  • 12
  • 14