Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito: return NULL on X call

Tags:

java

mockito

I have to mock BufferedReader to return values I want:

BufferedReader readerMock = mock(BufferedReader.class);
when(readerMock.readLine())
  .thenReturn("firstLine")
  .thenReturn("secondLine")
  .thenReturn(null);

for (String next = reader.readLine(); next != null; next = reader.readLine())
  do something...

Problem:

readerMock.readLine(); //returns "firstLine" 
readerMock.readLine(); //returns "secondLine"
readerMock.readLine(); //PROBLEM: returns "secondLine" instead of NULL

Question: How to return null on the third call

like image 378
VB_ Avatar asked Dec 07 '25 23:12

VB_


1 Answers

Works for me (Mockito 1.9.5):

BufferedReader readerMock = mock(BufferedReader.class);
when(readerMock.readLine())
  .thenReturn("firstLine")
  .thenReturn("secondLine")
  .thenReturn(null);

System.out.println(readerMock.readLine());
System.out.println(readerMock.readLine());
System.out.println(readerMock.readLine());

Output:

firstLine
secondLine
null
like image 61
Duncan Jones Avatar answered Dec 09 '25 11:12

Duncan Jones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!