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 :(
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With