简体   繁体   中英

Junit Test for InputStreamReader with Mockito

Can you please help me in writing the Junit test case for the below code?

public class ConsoleReader implements InputReader {
    public Cell readInput() {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Enter the co-ordinate Seperated by Comma");
            String coOrdinates = reader.readLine();
            String[] values=coOrdinates.split("\\,");
            return new Cell(Integer.parseInt(values[0]),Integer.parseInt(values[1]));
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return null;
    }
}
  1. Extract the reader as a field. (You can initiaize it either directly or in constructor)

     private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  2. Define a getter (either public or protected )

     protected BufferedReader getReader(){ return reader; }
  3. Remove initialization of new BufferedReader(...) from your method. Retrieve it using getReader() instead.

     public Cell readInput() { try { System.out.print("Enter the co-ordinate Seperated by Comma"); String coOrdinates = getReader().readLine(); String[] values=coOrdinates.split("\\\\,"); return new Cell(Integer.parseInt(values[0]),Integer.parseInt(values[1])); } catch (IOException ioe) { ioe.printStackTrace(); } return null; }
  4. In your test class initialize your ConsoleReader as Mockito.spy

     ConsoleReader consoleReader = spy(new ConsoleReader());
  5. Mock your getter

    private BufferedReader bufferedReader = mock(BufferedReader.class); @Before public void setUp() { doReturn(bufferedReader).when(consoleReader).getReader(); doCallRealMethod().when(consoleReader).readInput(); }
  6. Define your test:

     @Test public void testReadInput() { when(bufferedReader.readLine()).thenReturn("123,456"); Cell expectedCell = new Cell(123, 456); Cell actualCell = consoleReader.readInput(); assertEquals(expectedCell, actualCell); }

You can use Mockito to mock the BufferedReader, like the example below.

BufferedReader bufferedReader = Mockito.mock(BufferedReader.class);
Mockito.when(bufferedReader.readLine()).thenReturn("1", "2", "3");
// You can mock the result based on the type of result you are expecting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM