Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to throw IOException while reading a file using Mockito?

I have to throw an IOException using Mockito for a method, which is reading an input stream like given below. Is there any way to do it?

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

I tried mocking like

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

but didn't work out :(

like image 626
Balasubramanian Sankar Avatar asked Sep 26 '12 14:09

Balasubramanian Sankar


1 Answers

You're mocking a BufferedReader, but your method doesn't use your mock. It uses its own, new BufferedReader. You need to be able to inject your mock into the method.

It seems that inputStream is a field of the class containing this method. So you could mock the inputStream instead and make it throw an IOException when its read() method is called (by the InputStreamReader).

like image 86
JB Nizet Avatar answered Nov 15 '22 02:11

JB Nizet