I have createUser()
method in my UsserServiceImpl.java
public ResponseEntity<UserDto> createUser(UserDto userDto) {
User user = new User(userDto.getName(), userDto.getProducts(), getCurrentDate(), null);
user = repository.save(user);
return user != null ? new ResponseEntity<>(convertToDto(user), HttpStatus.OK) : new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
I have a unit test for this method
@Mock
private UserRepository userRepository;
private UserService userService;
@BeforeEach
void init() {
userService = new UserServiceImpl(userRepository);
}
@Test
void createUser() {
Set<Product> productSet = createProducts();
LocalDate date = getCurrentDate();
User user = new User("Max", productSet, date, null);
when(userRepository.save(user)).thenReturn(new User(UUID.fromString("e7485042-b46b-11e9-986a-b74e614de0b0"), "Max", productSet, date, null));
ResponseEntity<UserDto> userDto = userService.createUser(new UserDto("Max", productSet));
assertEquals(HttpStatus.OK, userDto.getStatusCode());
assertEquals(userDto.getBody(), new UserDto("Max", productSet));
}
When I execute test I get an `\\error:
org.opentest4j.AssertionFailedError: Expected :200 OK Actual :400 BAD_REQUEST
as I understand, the problem is that repository.save()
the method returns null.
I totally don`t understand why this string
when(userRepository.save(user))
.thenReturn(
new User(UUID.fromString("e7485042-b46b-11e9-986a-b74e614de0b0"),
"Max",
productSet,
date,
null)
);
doesn`t work properly, any help is appreciated!
It is because there are 2 User
objects being involved in this scenario. Inside createUser()
at runtime, there is a new User
object will be created. That User
object is not equal to the User
object you create when you write the Mock statement. Therefore, you can accept any arbitrary User
object when you define the mock statement.
Mockito.any(User.class)
If you intend those 2 objects to be equal; User
class should provide a proper equals()
implementation. It seems it doesn't provide such a implementation. So, you can try something like below.
when(userRepository.save(any(User.class)))
.thenReturn(
new User(UUID.fromString("e7485042-b46b-11e9-986a-b74e614de0b0"),
"Max",
productSet,
date,
null)
);
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.