Avatar ·

How to verify that a method was not called using Mockito?

Hi! I'm writing unit tests for a Java application using JUnit and Mockito. I have a service that, under certain conditions, should not call a method on a dependent object. For example, if the user is not authorized, the sendEmail() method should not be called. How can I verify this in a test?

Here's a simplified example of my code:

public class NotificationService {
    private EmailService emailService;

    public NotificationService(EmailService emailService) {
        this.emailService = emailService;
    }

    public void processUser(User user) {
        if (user.isActive()) {
            emailService.sendEmail(user.getEmail(), "Welcome!");
        }
    }
}

I wrote a test for the case when the user is active