lundi 4 février 2019

Java bad practice: adding return statement to method solely for testing?

Is it bad practice to add a return statement for the sole purpose of testing a method without using it in the actual code itself?

As an example case, I am testing a read method which is followed by a series of methods that eventually create an object with properties absorbed out of the lines of the file it is reading in.

From what I understood, a read method can be tested using Mockito without having to add a return statement. Or one could test whether another method (readPerLine) is called, but I have not yet found a proper testing procedure to do that. These two options could mean my general question is not relevant if proper coding procedure is used, if so please let me know.

However currently the following two options appear to be the most simple way to test (part of) the read method:

  1. Add a return statement that contains an array of the lines that the method read in, which is executed at the end of the method.
  2. Test the combination of the read method and the follow-up methods that create the objects by measuring whether the properties of the objects are correct. And by testing the follow up methods individually. This is not preferred as a double error, 1 in the read method and 1 in the conceptual design of the follow-up methods could cancel out during this testing, but cause errors in read life.
  3. Modifying the (read) method such that it returns an array of the lines, which is passed to the follow up methods from Main.

An example code of the read method that I currently wrote:

public void readFile(String filename) {
        FileReader reader;
        BufferedReader br;
        String line = null;
        try {       
            br = new BufferedReader(new FileReader(filename));

            while ((line = br.readLine()) != null) {
                readPerLine(line); //converts line into properties for an object.
            }  
            br.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

So I have not yet solved the following dilemma;

  • I know sometimes you need to rewrite your method to allow for testing.
  • But I do not know whether adding features, such as return statements that are not used by the actual code but only for testing, is good or bad practice. Additionally if I do that, I still do not completely test the read method, the calling another method is still not tested.
  • Or whether this dilemma should not at all occur if I apply proper etiquette in the first place.

Aucun commentaire:

Enregistrer un commentaire