UserDAO { public void create(User newUser) throws ValidationException, UnauthorizedException { if (userRepository.findOneByEmail(newUser.getEmail()) != null) { throw new ValidationException("A user with the email already exists"); } if (userRepository.findOneByUsername(newUser.getUsername()) != null) { throw new ValidationException("A user with this username already exists"); } if (!new EmailValidator().isValid(newUser.getEmail(), null)) { throw new ValidationException("The email is not valid"); } if (newUser.getUsername().length() > MAX_USERNAME_LENGTH || !newUser.getUsername().matches("^[a-zA-Z][a-zA-Z0-9]*$")) { throw new ValidationException("The username is not valid!"); } saveUser(newUser); } @Autowired  UserDAO(UserRepository userRepository, FileDAO fileDAO, ProjectDAO projectDAO,
                   ProjectRepository projectRepository); void create(User newUser); List<User> getAll(); List<User> getAllByRole(UserRole role); User getById(Long id); User getByEmail(String email); User getByUsername(String username); void update(User user); void delete(User authUser, Long id); void delete(User authUser, List<Long> userIds);  }
@Test public void shouldCreateAValidUser() throws NotFoundException { User user = createUser(); userDAO.create(user); Mockito.verify(userRepository).save(user); }
@Test(expected = ValidationException.class) public void shouldHandleTransactionSystemExceptionsOnUserCreationGracefully() { User user = createUser(); ConstraintViolationException constraintViolationException; constraintViolationException = new ConstraintViolationException("User is not valid!", new HashSet<>()); RollbackException rollbackException = new RollbackException("RollbackException", constraintViolationException); TransactionSystemException transactionSystemException; transactionSystemException = new TransactionSystemException("Spring TransactionSystemException", rollbackException); BDDMockito.given(userRepository.save(user)).willThrow(transactionSystemException); userDAO.create(user); }
@Test(expected = ValidationException.class) public void shouldHandleConstraintViolationExceptionOnUserCreationGracefully() { User user = createUser(); BDDMockito.given(userRepository.save(user)).willThrow(ConstraintViolationException.class); userDAO.create(user); }
@Test(expected = ValidationException.class) public void shouldHandleDataIntegrityViolationExceptionOnUserCreationGracefully() { User user = createUser(); BDDMockito.given(userRepository.save(user)).willThrow(DataIntegrityViolationException.class); userDAO.create(user); }