使用Mockito对InputStreamReader进行Junit测试

时间:2018-11-20 12:02:33

标签: java junit mockito

您能帮我为下面的代码编写Junit测试用例吗?

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;
    }
}

2 个答案:

答案 0 :(得分:2)

  1. reader提取为字段。 (您可以直接或在构造函数中对其进行初始化)

    private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    
  2. 定义吸气剂(publicprotected

    protected BufferedReader getReader(){
        return reader;
    }
    
  3. 从您的方法中删除new BufferedReader(...)的初始化。取而代之的是使用getReader()

    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. 在测试类中,将ConsoleReader初始化为Mockito.spy

    ConsoleReader consoleReader = spy(new ConsoleReader());
    
  5. 模拟您的吸气剂

    @Before
    public void setUp() {
        BufferedReader bufferedReader = mock(BufferedReader.class);
        doReturn(bufferedReader).when(consoleReader).getReader();
        doCallRealMethod().when(consoleReader).readInput();
    }
    
  6. 定义您的测试:

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

答案 1 :(得分:0)

您可以使用Mockito模拟BufferedReader,如下例所示。

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.