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?
CodePudding user response:
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");
}