简体   繁体   中英

How to use Mockito.verify with ignore one field?

I have a module:

class User {
   String id;
   double text;

   constructor (String id){
       this.id = id;
       this.text = Math.random();
   }
}

And a method:

class UserService{
    void saveUser(String id){
        User user = new User(id);
        userRepository.save(user);
    }
}

And for this code I want to make a Unit test:

@Test
void saveUserTest(){
    //Given
    User userTest = new User("123");

    //When
    UserService.saveUser("123");

    //Then
    Mockito.verify(userRepository).save(userTest);
}

and here I got a difference because User text was randomly generated.

So, how can I ignore the field text?

You can either ignore it using Mockito.any(User.class)

Mockito.verify(userRepo).save(Mockito.any(User.class));

or make use of Argument Captor to capture what was passed in and further assert that value if you want.

Something like so:

  @Captor
  private ArgumentCaptor<User> userArgumentCaptor;

  @Test
  void saveUserTest(){
    //Given
    User userTest = new User("123");

    //When
    userService.saveUser("123");

    //Then
    Mockito.verify(userRepo).save(userArgumentCaptor.capture());
    assert(userArgumentCaptor.getValue().getId()).equals("123");
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM