Mockito never() Method Example

1. Introduction

In Mockito, the never() method serves a specific purpose: it confirms that a particular interaction with a mock object has not occurred at all. Using never() can be beneficial to ascertain that certain actions, especially those that might have side effects or security implications, do not happen unexpectedly during testing.

2. Example Steps

1. Define an interface to represent an action we wish to test.

2. Implement this interface with a concrete class.

3. Set up a test class for our action.

4. Mock the interface using Mockito.

5. Verify using Mockito's never() method that a method on the mock was not called.

6. Run the test to validate the behavior.

3. Mockito never() Method Example

import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.never;

// Step 1: Define an interface
interface PaymentProcessor {
    void processPayment(double amount);
}

// Step 2: Implement the interface
class CreditCardProcessor implements PaymentProcessor {
    @Override
    public void processPayment(double amount) {
        System.out.println("Processed payment of amount: " + amount);
    }
}

public class PaymentTest {

    @Test
    public void testNoPaymentProcessed() {
        // Step 4: Mock the PaymentProcessor interface
        PaymentProcessor mockedProcessor = mock(PaymentProcessor.class);

        // Step 5: Use Mockito's never() method to ensure no payment was processed
        verify(mockedProcessor, never()).processPayment(anyDouble());
    }
}

Output:

The test will execute successfully, demonstrating that the processPayment method of the mocked object was never invoked.

4. Step By Step Explanation

1. We start by defining a PaymentProcessor interface to simulate a payment processing action.

2. The CreditCardProcessor class implements this interface by displaying the processed payment amount.

3. The heart of the testing action lies within the PaymentTest class. Here, we create a mock of the PaymentProcessor interface.

4. Notably, we don’t invoke the processPayment method on the mock at all.

5. We then leverage the combination of verify() and never() to validate that the processPayment method was not triggered during the test.

6. This type of validation is useful, especially in scenarios where you want to make sure some actions, that might cause side effects, are not mistakenly executed. For example, in a real-world scenario, you wouldn’t want to make accidental payments or trigger unwanted actions while testing.


Comments