Reputation: 2808
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:
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;
Upvotes: 0
Views: 228
Reputation: 3597
I would suggest that instead of adding a return statement to the method to enable testing, rather rework the method to separate some of the functionality.
I think the problem is here :
readPerLine(line); //converts line into properties for an object.
Maybe you're doing too much in this method. You could break this down into several different methods, for example :
If you did this you could check the functionality of each step and have tests for each.
When it comes to testing the main method readFile(String filename)
, you can then use Mokito to check that each method is called with the correct parameters
Upvotes: 1