我必须模拟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
答案 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