Alex Melillo
Alex Melillo

Reputation: 3

How can I unit test a method that requires keyboard input?

So I'm writing a static method that returns the average of all the grades you put in. Here's the code:

 public static float average() throws IOException {
        
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        float sum=0;
        
        System.out.print("Number of classes: ");
        int classes = Integer.parseInt(reader.readLine());
        
        for (int i = 0; i < classes; i++) {
            
            System.out.print("input the grade: ");
            float grade = Integer.parseInt(reader.readLine());
            
            sum += grade;
            
        }
        
        float average = sum / classes;
        
        return average;
    }

I want to perform tests in Junit to make sure this code is solid (The whole point here is to learn about JUNIT, I know the code itself isn't anything special).

The problem: this method requires that I input values via the keyboard in order to return something. I have no idea how I could change the input stream to take specific values in my junit tests. How would you recommend I go about it or what would you recommend I look into?

Upvotes: 0

Views: 352

Answers (1)

Sergej Masljukow
Sergej Masljukow

Reputation: 530

take BufferedReader out of your method, e.g. change signature of your method to

 public static float average(BufferedReader reader) throws IOException {}

and in your unit test give this method a reader, which reads from a file or from a string where you place required input values.

Upvotes: 4

Related Questions