Search code examples
javajunitjunit4

how to test the BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))


My method:

public class CalcService {

    double inputA = 0.0;

    @SneakyThrows
    public void firstNumber() {
       System.out.println("Input first number");
       BufferedReader firstNum = new BufferedReader(new InputStreamReader(System.in));
       inputA = Double.parseDouble(firstNum.readLine());
    }
}

how can I test this method to get double?

public class CalcServiceTest {

    double inputA = 0.0;
    
    @Test
    @SneakyThrows(IOException.class)
    public void firstNumberTest() {
        System.out.println("Input first number");
        BufferedReader secondNum = new BufferedReader(new InputStreamReader(System.in)); 
        inputA = Double.parseDouble(secondNum.readLine());
    }
}

test does not get input and pending corrected the inaccuracies


Solution

  • These methods are not very suitable for testing, as they interact directly with user input through the console and depend on the external environment. (Thanks Rob Spoor)

    I create a simulation of user input and transfer it into methods. I do this using the class java.io.ByteArrayInputStream.

    @Test
    public void testFirstNumber() {
        CalcService calc = new CalcService();
    
        // Configure the input flow using ByteArrayInputStream
        String input = "10.0\n"; // user input
        InputStream in = new ByteArrayInputStream(input.getBytes());
        System.setIn(in);
    
        calc.firstNumber(); // called tested method
    
        // Check that the entered value is correct
        assertEquals(10.0, calc.getInputA(), 0.001);
    }