thenReturn、doReturn 等函数支持链式调用,用来指定函数特定调用次数时的行为。
示例1:
import org.junit.Assert;
import org.junit.Test;
import static org.mockito.Mockito.*;
public class MockitoDemo {
static class ExampleService {
public int add(int a, int b) {
return a+b;
}
}
@Test
public void test() {
ExampleService exampleService = mock(ExampleService.class);
// 让第1次调用返回 100,第2次调用返回 200
when(exampleService.add(1, 2)).thenReturn(100).thenReturn(200);
Assert.assertEquals(100, exampleService.add(1, 2));
Assert.assertEquals(200, exampleService.add(1, 2));
Assert.assertEquals(200, exampleService.add(1, 2));
}
}
import org.junit.Assert;
import org.junit.Test;
import static org.mockito.Mockito.*;
public class MockitoDemo {
static class ExampleService {
public int add(int a, int b) {
return a+b;
}
}
@Test
public void test() {
ExampleService exampleService = mock(ExampleService.class);
// 让第1次调用返回 100,第2次调用返回 200
doReturn(100).doReturn(200).when(exampleService).add(1, 2);
Assert.assertEquals(100, exampleService.add(1, 2));
Assert.assertEquals(200, exampleService.add(1, 2));
Assert.assertEquals(200, exampleService.add(1, 2));
}
}