thenReturn 用来指定特定函数和参数调用的返回值。
比如:
import org.junit.Assert;
import org.junit.Test;
import static org.mockito.Mockito.*;
import java.util.Random;
public class MockitoDemo {
@Test
public void test() {
Random mockRandom = mock(Random.class);
when(mockRandom.nextInt()).thenReturn(1);
Assert.assertEquals(1, mockRandom.nextInt());
}
}
thenReturn 中可以指定多个返回值。在调用时返回值依次出现。若调用次数超过返回值的数量,再次调用时返回最后一个返回值。
import org.junit.Assert;
import org.junit.Test;
import static org.mockito.Mockito.*;
import java.util.Random;
public class MockitoDemo {
@Test
public void test() {
Random mockRandom = mock(Random.class);
when(mockRandom.nextInt()).thenReturn(1, 2, 3);
Assert.assertEquals(1, mockRandom.nextInt());
Assert.assertEquals(2, mockRandom.nextInt());
Assert.assertEquals(3, mockRandom.nextInt());
Assert.assertEquals(3, mockRandom.nextInt());
Assert.assertEquals(3, mockRandom.nextInt());
}
}