CodexBloom - Programming Q&A Platform

How do I mock a method in a class while testing with JUnit and Mockito?

👀 Views: 25 💬 Answers: 1 📅 Created: 2025-06-06
java junit mockito Java

I'm having trouble with unit testing a Java class that uses a dependency which I need to mock to isolate the class for testing. I’m using JUnit 5 and Mockito 3.11.2. My class, `UserService`, depends on a `UserRepository` class to fetch user data. I want to write a test for the `getUserById` method without actually calling the real `UserRepository`. Here’s the code for the `UserService`: ```java public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public User getUserById(Long id) { return userRepository.findById(id); } } ``` And here’s what I have for my test class: ```java import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; class UserServiceTest { @Mock private UserRepository userRepository; private UserService userService; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); userService = new UserService(userRepository); } @Test void testGetUserById() { User mockUser = new User(1L, "John Doe"); when(userRepository.findById(1L)).thenReturn(mockUser); User user = userService.getUserById(1L); assertEquals("John Doe", user.getName()); } } ``` When I run the test, I’m getting a `NullPointerException` because it seems that `userRepository` is not being properly mocked. I’ve verified that Mockito annotations are correctly initialized with `MockitoAnnotations.openMocks(this)`. I also tried using `@ExtendWith(MockitoExtension.class)` on my test class, but that didn't resolve the issue either. Any suggestions on what I might be missing or how I can better mock the `UserRepository` so that my test runs correctly?