使用springboot ebean时对服务层进行单元测试

问题描述 投票:0回答:1

env:Springboot ebean 作为 orm 服务层代码如下

@Service
@RequiredArgsConstructor
public class UserInfoServiceImpl implements UserInfoService {

    private final UserInfoRepository userInfoRepository;

    private final UserInfoMapper userInfoMapper;

    @Transactional
    @Override
    public UserInfoDTO save(UserInfoDTO userInfoDto) {
        UserInfo entity = convertToEntity(userInfoDto);
        entity.save();
        return convertToDTO(entity);
    }

    @Override
    public UserInfoDTO findById(Long userId) {
        return convertToDTO(UserInfo.find.byId(userId));
    }

    @Transactional
    @Override
    public UserInfoDTO update(UserInfoDTO userInfoDto) {
        UserInfo userInfo = convertToEntity(userInfoDto);
        userInfo.update();
        return convertToDTO(userInfo);
    }

    public UserInfoDTO convertToDTO(UserInfo userInfo) {
        return userInfoMapper.toDTO(userInfo);
    }

    public UserInfo convertToEntity(UserInfoDTO userInfoDTO) {
        return userInfoMapper.toEntity(userInfoDTO);
    }

    @Transactional
    @Override
    public void delete(Long userId) {
        UserInfo.find.deleteById(userId);
    }

    @Override
    public List<UserInfoDTO> list() {
        List<UserInfo> all = UserInfo.find.all();
        return userInfoMapper.toDTOList(all);
    }
}

问题1: 如何为活动记录编写单元测试(指保存方法) 问题2: 如何编写findById、更新、删除的单元测试 谢谢

或者也许我们不需要为这种方法编写单元测试

非常感谢

整个项目可以在这里找到github

ebean-mock 的一些帮助链接 ebean 模拟

unit-testing orm ebean
1个回答
0
投票

对于问题2,我在这里找到了解决方案 当想在 java 17 或更高版本中模拟静态最终字段时,可以使用下面的代码

    Field field = UserInfo.class.getField("find");
    final Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
    unsafeField.setAccessible(true);
    final Unsafe unsafe = (Unsafe) unsafeField.get(null);

    final Field ourField = UserInfo.class.getDeclaredField("find");
    final Object staticFieldBase = unsafe.staticFieldBase(ourField);
    final long staticFieldOffset = unsafe.staticFieldOffset(ourField);
    unsafe.putObject(staticFieldBase, staticFieldOffset, userInfoFinder);

这是参考链接帮助链接

© www.soinside.com 2019 - 2024. All rights reserved.