unit test for service layer when using springboot ebean

32 views Asked by At

env:Springboot ebean as orm service layer code like below

@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);
    }
}

question 1: how to write an unit test for active record (means the save method) question 2: how to write the unit test for findById, update,delete thanks

or maybe we don't need write a unit test for such kind of method

Thanks very much

the whole project could be found here github

some help link for ebean-mock ebean-mock

1

There are 1 answers

0
Johnson On

for question 2, I found a solution here when wanna mock a static final field in java 17 or above, you can use the code below

    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);

here is the reference link help link