例如:
1. 我有一个 Userservice 继承mybatisPlus的通用service, 默认就会实现了 getOne方法
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {
}
2. 我在controller 中调用
@GetMapping("/demo/user")
public String demostr() {
QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("u_id", "123");
UserEntity one = userService.getOne(queryWrapper);
return one.getUName();
}
3. 进行 junit mock
@Test
public void testService(@Mocked UserService userService) {
// new Expectations() {
// {
// UserService u2 = new UserServiceImpl();
// u2.getOne(new QueryWrapper<UserEntity>());
//// userService.getOne(new QueryWrapper<UserEntity>());
// UserEntity u = new UserEntity();
// u.setUId("123");
// u.setUName("456");
// result = u;
//// returns(u,u,u,u);
//// userService.aaa();
//// result = "nnn";
// }
// };
new MockUp<ServiceImpl<UserMapper, UserEntity>>() {
@Mock
public UserEntity getOne(Wrapper<UserEntity> userEntityWrapper) {
UserEntity u = new UserEntity();
u.setUId("123");
u.setUName("456");
return u;
}
};
Assertions.assertThat(userController.demostr())
.isEqualTo("456");
}
无论是使用 expectations 还是MockUP 都不行