title: How to mock JPA repository's save method in unit tests
body: <p>For example, I have this method in UserService:</p>
  
  <pre><code>  @Override
    @Transactional
    public UserDto create(UserDto userDto) {
  
      User dbUser = userRepository.findOne(userDto.getId());
  
      if (dbUser != null) {
        throw new AuthException(AuthException.ErrorCode.DUPLICATE_USER_EXCEPTION);
      }
  
      User oneByLogin = userRepository.findOneByLogin(userDto.getLogin());
      if (oneByLogin != null) {
        throw new AuthExceptionAuthException.ErrorCode.DUPLICATE_LOGIN_EXCEPTION);
      }
  
      User newUser = new User();
      newUser.setGuid(UUID.randomUUID().toString());
      newUser.setInsertDate(new Date());
      newUser.setFirstName(userDto.getFirstName());
      newUser.setLastName(userDto.getLastName());
      newUser.setLogin(userDto.getLogin());
      newUser.setPassword(userDto.getPassword());
      newUser.setAuthToken(TokenGenerator.nextToken());
      newUser.setAuthTokenCreatedDate(new Date());
  
      User savedUser = userRepository.save(newUser);
  
      userDto.setAuthToken(savedUser.getAuthToken());
      log.info("User {0} created", savedUser.getLogin());
      return userDto;
    }
  </code></pre>
  
  <p>How can I create unit test for this method? I tried next:</p>
  
  <pre><code>  @Test
    public void createUser() {
  
      UserDto userDtoRequest = new UserDto();
      userDtoRequest.setLogin("Alex");
      userDtoRequest.setPassword("123");
  
      UserDto found = userService.create(userDtoRequest);
      assertThat(found.getAuthToken()).isNotEmpty();
  }
  </code></pre>
  
  <p>I have next logic:</p>
  
  <ol>
  <li>Test start</li>
  <li><code>User dbUser = userRepository.findOne(userDto.getId());</code> dbUser = NULL</li>
  <li><code>if (dbUser != null</code>) and <code>if (oneByLogin != null)</code> skip</li>
  <li>create new user and set data</li>
  <li><code>User savedUser = userRepository.save(newUser);</code> savedUser = NULL</li>
  </ol>
  
  <p>On this step, I have a problem because I cannot mock <code>userRepository.save(newUser)</code>.</p>
  
  <pre><code>newUser create inside the method. and test fail.
  </code></pre>
  
  <p>savedUser.getAuthToken() - savedUser == NULL</p>
  
  <p>I can rewrite:</p>
  
  <pre><code>    userRepository.save(newUser);
      userDto.setAuthToken(newUser.getAuthToken());
      log.info("User {0} created", newUser.getLogin());
      return userDto;
  </code></pre>
  
  <p>but what if I want to use the returned object <code>savedUser</code>?</p>