0
0
JunitHow-ToBeginner ยท 3 min read

How to Use verify in Mockito with JUnit Tests

In JUnit tests, use Mockito.verify(mockObject) to check if a method was called on a mock. You specify the method and arguments after verify(mockObject) to confirm interactions happened as expected.
๐Ÿ“

Syntax

The basic syntax of verify in Mockito is:

  • verify(mockObject).methodName(arguments); - checks if methodName was called on mockObject with the given arguments.
  • You can add times(n) to check how many times the method was called, e.g., verify(mockObject, times(2)).methodName(args);.
  • Use never() to assert a method was not called.
java
verify(mockObject).someMethod("arg");
verify(mockObject, times(3)).someMethod("arg");
verify(mockObject, never()).someMethod("arg");
๐Ÿ’ป

Example

This example shows how to create a mock, call a method on it, and verify that the method was called once with the expected argument.

java
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;

class Service {
    void perform(String input) {}
}

public class VerifyExampleTest {

    @Test
    void testVerifyMethodCalled() {
        Service mockService = mock(Service.class);

        // Call method on mock
        mockService.perform("hello");

        // Verify method was called once with "hello"
        verify(mockService).perform("hello");
    }
}
Output
Test passes with no errors if method was called as verified.
โš ๏ธ

Common Pitfalls

  • Not calling the method on the mock before verify causes test failure.
  • Using real objects instead of mocks with verify will throw errors.
  • Forgetting to import static Mockito methods can cause compilation issues.
  • Verifying with wrong arguments or wrong number of calls leads to test failures.
java
/* Wrong: method not called before verify */
Service mockService = mock(Service.class);
// verify(mockService).perform("hello"); // Fails because perform not called

/* Right: call method before verify */
mockService.perform("hello");
verify(mockService).perform("hello");
๐Ÿ“Š

Quick Reference

UsageDescription
verify(mock).method(args);Check method called once with args
verify(mock, times(n)).method(args);Check method called n times
verify(mock, never()).method(args);Check method never called
verifyNoMoreInteractions(mock);Check no other methods called on mock
โœ…

Key Takeaways

Use verify(mock).method(args) to check method calls on mocks in JUnit tests.
Always call the method on the mock before verifying it to avoid test failures.
Use times(n) with verify to check how many times a method was called.
Never use verify on real objects; only use it on mocks created by Mockito.
Import static Mockito methods to write clean and readable verify statements.