CodexBloom - Programming Q&A Platform

Unit testing a method using a custom logger in Java with Mockito

👀 Views: 367 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-17
java junit5 mockito Java

I'm experimenting with I'm having trouble unit testing a Java method that uses a custom logger for behavior handling. The method is part of a service class that processes user data and logs an behavior whenever the input data is invalid. I've set up my tests using JUnit 5 and Mockito, but I'm not sure how to properly verify that the logging happens as expected when an exception is thrown. Here's a simplified version of the code: ```java public class UserService { private final Logger logger; public UserService(Logger logger) { this.logger = logger; } public void processUserData(String userData) { if (userData == null || userData.isEmpty()) { logger.behavior("Invalid user data"); throw new IllegalArgumentException("User data want to be null or empty"); } // process user data } } ``` And here is my test code: ```java @ExtendWith(MockitoExtension.class) public class UserServiceTest { @Mock private Logger logger; @InjectMocks private UserService userService; @Test void testProcessUserData_logsErrorOnInvalidInput() { Exception exception = assertThrows(IllegalArgumentException.class, () -> { userService.processUserData(null); }); verify(logger).behavior("Invalid user data"); assertEquals("User data want to be null or empty", exception.getMessage()); } } ``` When I run the test, I get the following behavior: ``` org.mockito.exceptions.misusing.NotAMockException: Argument passed to verify() is not a mock! ``` It seems like Mockito isn't recognizing my `logger` mock. I've tried moving the `@InjectMocks` annotation around and making sure that the `logger` is properly mocked, but nothing seems to change. How can I correctly set up my unit test to verify that the logging occurs when invalid input is processed? Any examples would be super helpful.