示例
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);
// 设置让 add(1,2) 返回 100
when(exampleService.add(1, 2)).thenReturn(100);
exampleService.add(1, 2);
// 校验是否调用过 add(1, 2) -> 校验通过
verify(exampleService).add(1, 2);
// 校验是否调用过 add(2, 2) -> 校验不通过
verify(exampleService).add(2, 2);
}
}
示例:
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次调用
exampleService.add(1, 2);
// 校验是否调用过一次 add(1, 2) -> 校验通过
verify(exampleService, times(1)).add(1, 2);
// 第2次调用
exampleService.add(1, 2);
// 校验是否调用过两次 add(1, 2) -> 校验通过
verify(exampleService, times(2)).add(1, 2);
}
}
( 本文完 )