UserService { @Transactional public User register(RegisterDto registerDto) { if(isUsernameExist(registerDto.getUsername(), Optional.empty())) { throw new AppBusinessException(UserErrorCode.UsernameExist, String.format("用户名%s已存在", registerDto.getUsername())); } User user = new User(); user.setUsername(registerDto.getUsername()); try { user.setPassword(PasswordHash.createHash(registerDto.getPassword())); } catch (GeneralSecurityException e) { logger.error("创建哈希密码的时候发生错误", e); throw new AppBusinessException("用户注册失败"); } userRepository.save(user); eventBus.publish(new UserCreated(user.getId(), user.getUsername(), user.getCreateTime())); return user; }  @Transactional void save(User user); @Transactional(readOnly = true) Optional<User> getById(Long userId); @Transactional User register(RegisterDto registerDto); @Transactional(readOnly = true) boolean isUsernameExist(String username, Optional<Integer> userId);  }
@Test public void testRegister() { RegisterDto registerDto = new RegisterDto(); registerDto.setUsername(RandomStringUtils.randomAlphanumeric(8)); registerDto.setPassword(RandomStringUtils.randomAlphanumeric(8)); User user = userService.register(registerDto); assertThat(user.getId(), notNullValue()); Optional<User> userOp = userService.getById(user.getId()); assertThat(userOp.isPresent(), is(true)); try { userService.register(registerDto); throw new AssertionError("使用重复用户名注册成功: " + registerDto.getUsername()); } catch(AppBusinessException expected) { } }