How to properly mock a method in a unit test using Mockito 4.0.0 without causing NullPointerException?
I'm working on a project and hit a roadblock. I've been banging my head against this for hours. I'm sure I'm missing something obvious here, but Hey everyone, I'm running into an issue that's driving me crazy. I'm currently working on a Java application using Spring Boot 2.6.0, and I'm having trouble with my unit tests when trying to mock a method using Mockito 4.0.0. Specifically, I have a service class that calls a repository method, and when I try to mock this repository in my test, I'm getting a `NullPointerException` when the mocked method is invoked. Hereβs a simplified version of my service class: ```java @Service public class UserService { private final UserRepository userRepository; @Autowired public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public User getUserById(Long id) { return userRepository.findById(id) .orElseThrow(() -> new UserNotFoundException("User not found")); } } ``` And here is my unit test: ```java @RunWith(MockitoJUnitRunner.class) public class UserServiceTest { @Mock private UserRepository userRepository; @InjectMocks private UserService userService; @Test public void testGetUserById_UserExists() { User user = new User(); // Assume this is a valid User object with necessary fields Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(user)); User result = userService.getUserById(1L); assertNotNull(result); assertEquals(user, result); } } ``` When I run the test, I encounter this behavior: ``` java.lang.NullPointerException: want to invoke "java.util.Optional.get()" because "this.userRepository.findById(id)" is null ``` I've verified that I'm using the correct versions of Mockito and Spring Boot. My question seems to stem from how I'm trying to inject the mocks. I've also tried using `@Before` to initialize mocks, but I still end up with the same exception. Can anyone help clarify what I'm doing wrong and how to properly set up the mocking in this scenario? It seems like a straightforward test but I'm getting exploring on this NullPointerException. Any ideas what could be causing this? What am I doing wrong? I'm working on a application that needs to handle this. Is there a better approach? My development environment is macOS. How would you solve this?