Home > Software engineering >  Mocking InputStream, InputStreamReader and BufferedReader
Mocking InputStream, InputStreamReader and BufferedReader

Time:04-27

I have the following piece of code :

InputStream inputStream = sftpConfig.getSftpChannel().get(fileAbsolutePath);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)))
String line = bufferedReader.readLine();

All I want is to mock these lines, and be flexible in bufferedReader.readLine(), because I will have several test cases depending on the lines (a case where the file is empty and the line is null, a case where I get only one line, a case where I get several etc.).

Note : I am using jsch library for accessing files on FTP servers, so the method getSftpChannel() has ChannelSftp as return type, and get(fileAbsolutePath) has InputStream.

I am using junit 4.12 and mockito 3.1.0

Thanks in advance!

CodePudding user response:

It's probably easier just to instantiate ByteArrayInputStream instance instead of mocking it and filling it with data you need, e.g.

var stream = new ByteArrayInputStream("hello".getBytes());

and you can just use that in place of your InputStream.

  • Related