Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Strange Mockito verify fail

I am testing my java app with Mockito, all good until this strange fail test.
enter image description here
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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

  1. pass user as-is into repository.save, without creating new instance
  2. define equals on User class to be equals on name field
  3. Update assertion to capture (using ArgumentCaptor) and then verify captured object
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading