Fail Test SpringBootTest with error "java.lang.NullPointerException: Cannot invoke..."

140 Views Asked by At

I am doing test writing for user search function in UserService. I get the error "java.lang.NullPointerException: Cannot invoke "com.javaspring.blogapi.repository.UserRepository.findByUsername(String)" because "this.userRepository" is null", I have 3 classes:

  • UserRepo
  • UserService
  • UserServiceTest I use Springboot 3.1.0

Here is my code:

-Repo class:

@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
    UserEntity findByUsername(String userName);
    UserEntity findByVerifyCodeEmail(String code);
}

-Service class:

@Override
public UserDTO findByUsername(String username) {
    UserEntity user = userRepository.findByUsername(username);
    if (user == null) throw new CustomException.NotFoundException("Không tìm thấy người dùng " + username);
    return userConverter.UserToUserDTO(user);
}

-Test class:

@ExtendWith(MockitoExtension.class)
@SpringBootTest
public class UserServiceTest {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserConverter userConverter;
    @InjectMocks
    private UserService userService;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.openMocks(this);
    }

    @Test
    public void findByUsername200() throws Exception {
        String name = "[email protected]";

        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(name);

        when(userRepository.findByUsername(name)).thenReturn(userEntity);

        UserDTO expectedResult = userConverter.UserToUserDTO(userEntity);

        UserDTO actualResult = userService.findByUsername(name);

        assertEquals(expectedResult, actualResult);

        System.out.println(name);
    }
}
0

There are 0 best solutions below