when(mockLinkedList.get(0)).thenReturn("first")
// 理解:将每一个元素设置为"first" 在需要的使用每0个元素时就返回值为“first”
verify(mockLinkedList).get(0)
// 理解:验证get(0)被调用的次数
版本 | 方式一 | 方式二 | 方式三 |
---|---|---|---|
Junit4 | @RunWith(MockitoJunitRunner.class) | Mockito.mock(xx.class)/Mockito.spy(xx.class) | MockitoAnnotations.openMocks(class)+@Mock注解 |
Junit5 | @ExtendWith(MockitoExtension.class) | Mockito.mock(xx.class)/Mockito.spy(xx.class) | MockitoAnnotations.openMocks(class)+@Mock注解 |
// Setup
final List<DriverBo> expectedResult =
Arrays.asList(
DriverBo.builder()
.id(0L)
.contactInformations(Arrays.asList(DriverContactInformationBo.builder().build()))
.build());
// 调用queryList方法时,直接返回指定的数据
Mockito.doReturn(Arrays.asList(Convert.toList(expectedResult)))
.when(driverServiceImplUnderTest)
.queryList(Arrays.asList(0L));
// Run the test
final List<DriverBo> result = driverServiceImplUnderTest.queryList(Arrays.asList(0L));
// Verify the results
assertThat(result.size()).isEqualTo(expectedResult.size());
// 使用mockito对象时,真实调用目标方法
Mockito.when(xxService.method(arg))
.thenCallRealMethod();
// 自定义插桩逻辑,invocation可以拿到对应的调用方法,mock对象,入参等信息
Mockito.doAnswer(
new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object argument = invocation.getArgument(0);
return 1;
}
})
.when(driverServiceImplUnderTest)
.queryById(0L);
@Test
public void list() {
// mock creation 创建mock对象
List mockedList = mock(List.class);
// using mock object 使用mock对象
mockedList.add("one");
mockedList.clear();
// verification 验证
verify(mockedList).add("one");
verify(mockedList).clear();
}
@Test
public void linkedList() {
LinkedList mockLinkedList = mock(LinkedList.class);
RuntimeException runtimeException = new RuntimeException();
// 打桩测试
when(mockLinkedList.get(0)).thenReturn("first");
when(mockLinkedList.get(1)).thenReturn(runtimeException);
// 验证结果
Assertions.assertEquals("first", mockLinkedList.get(0));
Assertions.assertEquals(runtimeException, mockLinkedList.get(1));
// 验证
verify(mockLinkedList, times(1)).get(1);
}
public class UserDao {
public User queryByName(String name) {
System.out.println(name);
return User.builder().id(5).name(name).build();
}
public Integer save(User user) {
return 1;
}
public void update(User user) {}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class User {
private Integer id;
private String name;
}
public class UserService {
private UserDao userDao = new UserDao();
/**
* 新增一个用户
*
* @param name
* @return
*/
public Integer save(String name) throws Exception {
if (StrUtil.isBlank(name)) {
throw new ValidationException("名称不能为空");
}
User user = userDao.queryByName(name);
if (user != null) {
throw new Exception("用户已存在,请不要重复添加");
}
Integer id = userDao.save(user);
return id;
}
}
class UserServiceTest {
@Mock private UserDao userDao;
@InjectMocks @Spy private UserService userService;
@BeforeEach
void before() {
MockitoAnnotations.openMocks(this);
}
@Test
void save() throws Exception {
String name = null;
// 名字为空
try {
userService.save(name);
Assertions.fail("这里会挂");
} catch (Exception e) {
Assertions.assertTrue(e instanceof ValidationException);
}
// 设置值走正常流程
name = "gzwen";
// 正常流程
Mockito.doReturn(null).when(userDao).queryByName(name);
Mockito.when(userService.save(name)).thenReturn(1);
Integer newUserId = userService.save(name);
Assertions.assertEquals(1, newUserId);
// 用户已存在,不允许重新插入,抛出异常
Mockito.doReturn(new User()).when(userDao).queryByName(name);
try {
userService.save(name);
Assertions.fail("这里会挂");
} catch (Exception e) {
Assertions.assertTrue(e instanceof Exception);
}
// 用户已存在,不允许重新插入,抛出异常;输入任意参数都返回一个空user 对象
Mockito.doReturn(new User()).when(userDao).queryByName(Mockito.any());
try {
userService.save(name);
Assertions.fail("这里会挂");
} catch (Exception e) {
Assertions.assertTrue(e instanceof Exception);
}
}
}
<dependency>
<groupId>org.mockitogroupId>
<artifactId>mockito-inlineartifactId>
<version>4.3.1version>
<scope>testscope>
dependency>
public class StaticUtils {
public StaticUtils() {}
public static List<Integer> range(int tart, int end) {
return IntStream.range(tart, end).boxed().collect(Collectors.toList());
}
public static String name() {
return "Echo";
}
}
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock private UserDao userDao;
@InjectMocks @Spy private UserService userService;
@Test
void save() throws Exception {
String name = null;
// 名字为空
try {
userService.save(name);
Assertions.fail("这里会挂");
} catch (Exception e) {
Assertions.assertTrue(e instanceof ValidationException);
}
// 设置值走正常流程
name = "gzwen";
// 正常流程
Mockito.doReturn(null).when(userDao).queryByName(name);
Mockito.when(userService.save(name)).thenReturn(1);
Integer newUserId = userService.save(name);
Assertions.assertEquals(1, newUserId);
// 用户已存在,不允许重新插入,抛出异常
Mockito.doReturn(new User()).when(userDao).queryByName(name);
try {
userService.save(name);
Assertions.fail("这里会挂");
} catch (Exception e) {
Assertions.assertTrue(e instanceof Exception);
}
// 用户已存在,不允许重新插入,抛出异常;输入任意参数都返回一个空user 对象
Mockito.doReturn(new User()).when(userDao).queryByName(Mockito.any());
try {
userService.save(name);
Assertions.fail("这里会挂");
} catch (Exception e) {
Assertions.assertTrue(e instanceof Exception);
}
}
}
如果你访问github网站比较慢,或者一些资源无法访问你可以看一下这里:网络加速器