Mockito:在X调用时返回NULL

时间:2014-06-17 18:03:52

标签: java mockito

我必须模拟BufferedReader才能返回我想要的值:

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...

问题:

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

问题:如何在第三次通话中返回null

1 个答案:

答案 0 :(得分:3)

适合我(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());

输出:

firstLine
secondLine
null