I am trying to do a unit test into the service layer with Mockito, JUnit 5 and Spring Boot but I get NullPointerException.
This is my test class:
class UserServiceTest {
@Mock
UserRepository userRepository;
@InjectMocks
IUserService userService;
UserMapper userMapper;
@Test
void when_save_user_it_should_return_user(){
UserRequest userRequest = UserRequest.builder()
.email("[email protected]")
.password("123456")
.firstName("Pedro")
.lastName("Perez")
.birthDate(LocalDateTime.now())
.imageUrl("")
.currency("170")
.build();
Mockito.when(userRepository.save(Mockito.any(UserEntity.class))).thenReturn(new UserEntity());
UserEntity createdUser = userService.createUser(userRequest);
assertThat(createdUser.getFirstName()).isSameAs(userRequest.getFirstName());
}
}
And this is my response:
java.lang.NullPointerException
at com.jhapdevelopment.moneyhub.usermicroservice.services.implementations.UserServiceTest.when_save_user_it_should_return_user(UserServiceTest.java:41)
I don't understand why I get this response, I mean maybe Is it possible that be a problem with dependency
CodePudding user response:
I guess mocking does not injecting correctly.
For JUnit 5, you must use @ExtendWith(MockitoExtension.class)
on top of the class.
CodePudding user response:
@InjectMocks IUserService userService -> replace with UserServiceImpl