### Question:
UserService extends
    PersonService<E, D> { public E persistNewUser(E user, boolean encryptPassword) { if (user.getId() != null) { return user; } if (encryptPassword) { user.setPassword(passwordEncoder.encode(user.getPassword())); } dao.saveOrUpdate(user); return user; } @SuppressWarnings("unchecked")  UserService(); protected  UserService(Class<E> entityClass); @Override @Autowired @Qualifier("userDao") void setDao(D dao); @PostAuthorize("hasRole(@configHolder.getSuperAdminRoleName()) or hasPermission(#accountName, 'READ')") @Transactional(readOnly = true) E findByAccountName(String accountName); @PostAuthorize("hasRole(@configHolder.getSuperAdminRoleName()) or hasPermission(#email, 'READ')") @Transactional(readOnly = true) E findByEmail(String email); E registerUser(E user, HttpServletRequest request); @SuppressWarnings("unchecked") void activateUser(String tokenValue); E persistNewUser(E user, boolean encryptPassword); void updatePassword(E user, String rawPassword); @Transactional(readOnly = true) E getUserBySession(); @PostFilter("hasRole(@configHolder.getSuperAdminRoleName()) or hasPermission(filterObject, 'READ')") @Transactional(readOnly = true) Set<UserGroup> getGroupsOfUser(Integer userId); PasswordEncoder getPasswordEncoder(); void setPasswordEncoder(PasswordEncoder passwordEncoder); Role getDefaultUserRole(); void setDefaultUserRole(Role defaultUserRole);  }### Answer:
@Test public void persistNewUser_shouldPersistAndEncrypt() { String rawPassword = "p@sSw0rd"; boolean encryptPassword = true; User unpersistedUser = new User(); unpersistedUser.setPassword(rawPassword); doNothing().when(dao).saveOrUpdate(any(User.class)); User persistedUser = crudService.persistNewUser(unpersistedUser, encryptPassword); verify(dao, times(1)).saveOrUpdate(any(User.class)); verifyNoMoreInteractions(dao); assertTrue(passwordEncoder.matches(rawPassword, persistedUser.getPassword())); }
@Test public void persistNewUser_shouldPersistButNotEncrypt() { String password = "p@sSw0rd"; boolean encryptPassword = false; User unpersistedUser = new User(); unpersistedUser.setPassword(password); doNothing().when(dao).saveOrUpdate(any(User.class)); User persistedUser = crudService.persistNewUser(unpersistedUser, encryptPassword); verify(dao, times(1)).saveOrUpdate(any(User.class)); verifyNoMoreInteractions(dao); assertEquals(password, persistedUser.getPassword()); }
@Test public void persistNewUser_doesNothingIfUserHasId() throws NoSuchFieldException, IllegalAccessException { String rawPassword = "p@sSw0rd"; boolean encryptPassword = true; Integer userId = 42; User unpersistedUser = new User("Dummy", "User", "dummyuser"); unpersistedUser.setPassword(rawPassword); IdHelper.setIdOnPersistentObject(unpersistedUser, userId); User persistedUser = crudService.persistNewUser(unpersistedUser, encryptPassword); verifyNoMoreInteractions(dao); assertEquals(unpersistedUser, persistedUser); }