UserServiceImpl implements UserService { @Transactional @Override public Long saveOrUpdate(UserDTO userDTO) { Assert.notNull(userDTO); UserEntity entity = converterService.convert(userDTO, UserEntity.class); try { return userRepository.saveAndFlush(entity).getId(); } catch (ConstraintViolationException | DataIntegrityViolationException ex) { log.error("Save to repository failed.", ex); String userName = entity.getUserName(); throw new DuplicateRecordException(userName, "Duplication occurred when saving user: " + userName, ex); } }  @Transactional(readOnly = true) UserDTO login(UserDTO user); @Transactional @Override Long saveOrUpdate(UserDTO userDTO); @Transactional(readOnly = true) @Override UserDTO findUserByName(String username);  }
@Test(expected = IllegalArgumentException.class) public void saveOrUpdateShouldThrowIllegalArgumentExceptionBecauseNullParameter() { userService.saveOrUpdate(NULL_USER_DTO); }
@Test(expected = DuplicateRecordException.class) public void saveOrUpdateShouldThrowDuplicateRecordExceptionBecauseOfConstraintViolationException() { given(userRepository.saveAndFlush(userEntity)).willThrow(ConstraintViolationException.class); userService.saveOrUpdate(detailedUserDTO); }
@Test(expected = DuplicateRecordException.class) public void saveOrUpdateShouldThrowDuplicateRecordExceptionBecauseOfDataIntegrityViolationException() { given(userRepository.saveAndFlush(userEntity)).willThrow(DataIntegrityViolationException.class); userService.saveOrUpdate(detailedUserDTO); }
@Test public void saveOrUpdateShouldReturnUserId() { given(userRepository.saveAndFlush(userEntity)).willReturn(userEntity); Long result = userService.saveOrUpdate(detailedUserDTO); then(converterService).should().convert(detailedUserDTO, UserEntity.class); then(userRepository).should().saveAndFlush(userEntity); assertThat(result, is(USER_ID)); }