Avatar ·

Difference between @Mock and @InjectMocks in Mockito: when and what to use?

Hi everyone! I'm a beginner Java developer writing unit tests using Mockito and Spring. I'm confused about the @Mock and @InjectMocks annotations. I read the documentation but still don't fully understand the difference and when to use which.\n\nLet's say I have a UserService that uses UserRepository and EmailService. I want to test the registerUser() method in UserService, which calls the repository to save the user and then sends an email.\n\nHere's an example of my class:\n\n```java\npublic class UserService {\n private UserRepository userRepository;\n private EmailService emailService;\n\n public UserService(UserRepository userRepository, EmailService emailService) {\n this.userRepository = userRepository;\n this.emailService = emailService;\n```