I have an User class:
public class User {
private Long id;
private String ssn;
private float height;
private float weight;
}
And an UpdateUserDTO class:
public class UpdateUserDTO {
private float height;
private float weight;
}
And an UserDTO class:
public class UserDTO {
private Long id;
private float height;
private float weight;
}
I've used Model Mapper to map the updated fields from updateUserDTO to user, which comes from the DB.
@Service
public class UserServiceImpl implements UserService {
private final UserRepository repository;
private final ModelMapper mapper;
public UserDTO update(long userId, UpdateUserDTO updateUserDTO) {
User user = getUserById(userId);
mapper.map(updateUserDTO, user);
user = repository.save(user);
return mapper.map(user, UserDTO.class);
}
}
My test class looks like this:
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@InjectMocks
private UserServiceImpl service;
@Mock
private ModelMapper mapper;
@Test
void updateWithSuccess() {
long userId = 1L;
UpdateUserDTO requestUpdateUserDTO = UpdateUserDTO.builder().height(1f).weight(1f).build();
User userFromDB = User.builder().id(1L).ssn("123").height(50f).weight(50f).build();
User userAfterMap = User.builder().id(1L).ssn("123").height(50f).weight(50f).build();
UserDTO response = UserDTO.builder().id(1L).height(50f).weight(50f).build();
Mockito.when(repository.findById(userId)).thenReturn(Optional.of(userFromDB));
Mockito.when(mapper.map(requestUpdateUserDTO, userFromDB)).thenReturn(userAfterMap);
Mockito.when(repository.save(userFromDB)).thenReturn(userFromDB);
Mockito.when(mapper.map(userFromDB, UserDTO.class)).thenReturn(response);
}
service.update(userId, requestUpdateUserDTO);
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
assertEquals(requestUpdateUserDTO.getHeight(), userCaptor.getValue().getHeight());
assertEquals(requestUpdateUserDTO.getWeight(), userCaptor.getValue().getWeight());
}
But the first Mockito.when() line does not even compile, because mapper.map() is a void method, so it does not expect any return values.
I've also tried:
Mockito.when(mapper.map(any(), any())).thenReturn(updatedUser);
Which does compile, but the mapper.map() doesn't work at all. Any of the fields are updated.
I've also tried:
Mockito.doReturn(updatedUser).when(mapper).map(any(), any());
But it doesn't work either.
I receive the error:
org.opentest4j.AssertionFailedError:
Expected :5.0
Actual :3.0
That's because mapper.map() does not work.
Does anyone know how I can mock this Mapper properly?
Thanks!