How to throw an IOException while reading a file using Mockito?

I need to start IOExceptionusing Mockito for a method that reads an input stream as follows. Is there any way to do this?

public void someMethod(){
 try{
  BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
  firstLine = in.readLine();
 }catch(IOException ioException){
  //Do something
 }

I tried to mock how

  BufferedReader buffReader = Mockito.mock(BufferedReader.class);
  Mockito.doThrow(new IOException()).when(buffReader).readLine();

but failed: (

+5
source share
3 answers

You are mocking BufferedReader, but your method does not use your layout. It uses its own, new BufferedReader. You must be able to enter your layout into the method.

It seems to be the inputStreamfield of the class containing this method. That way you can mock inputStream and make it throw an IOException when its method read()is called (via InputStreamReader).

+7

BufferedReader , .

inputStream InputStream.read().

+2

, , - , BufferedReader. , , .

public class BufferedReaderFactory{
  public BufferedReader makeBufferedReader(InputStream input) throws IOException{
    return new BufferedReader(new InputStreamReader(input));
  }
}

BufferedReaderFactory - , . BufferedReaderFactory . someMethod() makeBufferedReader() new.

; , mocked BufferedReaderFactory , someMethod(). makeBufferedReader, , .

, , , . Mockito; .

, , .

+1

All Articles