Mocking Java InputStream

前端 未结 10 1697
既然无缘
既然无缘 2020-11-29 04:40

Please provide pointers to help me mock that java InputStream object. This is the line of code that I would wish to Mock:

InputStreamReader inputData = new I         


        
10条回答
  •  情书的邮戳
    2020-11-29 05:00

    Change your object so it is easier to test, something like this:

    public MyObject {
        private InputStream inputStream;
    
        public void setInputStream(InputStream inputStream) {this.inputStream = inputStream;}
    
        public void whatever() {
            InputStreamReader inputData = new InputStreamReader(inputStream);
            bufferdReader = new BufferedReader(inputData);
            bufferdReader.readLine(); 
        }
    }
    

    then when you use your object initialize its inputStream first:

    MyObject myObject = new MyObject();
    myObject.setInputStream(System.in);
    

    Now you have an object where you can test it using any implementation of InputStream you want (ByteArrayInputStream is a good one to try).

提交回复
热议问题