I am testing my java app with Mockito, all good until this strange fail test.

As you can see there is an extra blank space at the end of the line.
This is my createUser method.
@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user) {
try {
User _user = userRepository.save(new User(user.getName()));
return new ResponseEntity<>(_user, HttpStatus.CREATED);
}
catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
And my UserRepository :
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findAll();
List<User> findByName(String name);
}
I tried to search for this but nothing related found, if someone can help me with a related post.
>Solution :
In line User _user = userRepository.save(new User(user.getName())); new instance of User is created.
Mostly likely there is no custom equals implementation in User class – and as by default it would return false for 2 different instances, even if they contain same data.
3 ways to solve:
- pass user as-is into repository.save, without creating new instance
- define equals on User class to be equals on name field
- Update assertion to capture (using ArgumentCaptor) and then verify captured object