Tuesday, January 21, 2025
HomeProgrammingWhat Are The Methods of Mockito?

What Are The Methods of Mockito?

Mockito is a popular mocking framework used in unit testing in Java. It allows you to mock objects and verify interactions, making it easier to test units of code in isolation. Here are the main methods provided by Mockito:

1. Mocking Objects

  • mock(Class<T> classToMock): Creates a mock of the specified class or interface.
    List<String> mockList = mock(List.class);
    
  • mockStatic(Class<T> classToMock) (Introduced in Mockito 3.4.0): Mocks static methods for the specified class.
    try (MockedStatic<MyClass> mockedStatic = mockStatic(MyClass.class)) {
        mockedStatic.when(MyClass::staticMethod).thenReturn("Mocked value");
    }
    

2. Stubbing Methods

  • when(T methodCall): Stubs a method to return a specific value when it’s called.
    when(mockList.get(0)).thenReturn("Hello");
    
  • thenReturn(T value): Specifies the value to be returned when a method is called.
    when(mockList.get(0)).thenReturn("Mocked Response");
    
  • thenThrow(Throwable... throwable): Defines an exception to be thrown when a method is called.
    when(mockList.get(0)).thenThrow(new RuntimeException("Exception"));
    
  • thenAnswer(Answer): Defines a custom answer for a method call, allowing for more complex behaviors.
    when(mockList.get(0)).thenAnswer(invocation -> "Custom Answer");
    

3. Verifying Interactions

  • verify(T mock): Verifies if a method on a mock object was called.
    verify(mockList).get(0);
    
  • verify(T mock, times(int)): Verifies how many times a method was called.
    verify(mockList, times(2)).get(0);
    
  • verifyNoMoreInteractions(T mock): Verifies that no other interactions were made with the mock object.
    verifyNoMoreInteractions(mockList);
    
  • verifyZeroInteractions(T mock): Verifies that no interactions were made with the mock object.
    verifyZeroInteractions(mockList);
    

4. Argument Matchers

  • any(Class<T> clazz): Matches any argument of the specified type.
    when(mockList.add(any(String.class))).thenReturn(true);
    
  • eq(T value): Matches the exact value.
    when(mockList.get(eq(1))).thenReturn("Item 1");
    
  • anyInt(), anyString(), anyDouble(), etc.: Specific matchers for primitive types.
    when(mockList.contains(anyString())).thenReturn(true);
    

5. Spying on Real Objects

  • spy(T object): Creates a spy, which is a partial mock that can call real methods while still allowing for stubbing.
    List<String> spyList = spy(new ArrayList<>());
    
  • doReturn(T value).when(T mock).method(): Used with spies to avoid calling real methods in some cases (useful for void methods or to avoid real execution).
    doReturn("Mocked Response").when(spyList).get(0);
    

6. Resetting Mocks

  • reset(T mock): Resets a mock object, clearing its state and interactions.
    reset(mockList);
    

7. Capturing Arguments

  • ArgumentCaptor: Captures arguments passed to mock methods.
    ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class);
    verify(mockList).add(argumentCaptor.capture());
    String capturedArgument = argumentCaptor.getValue();
    

8. Timeout for Verifications

  • verify(T mock, timeout(long)): Verifies that a method was called within a specific time frame.
    verify(mockList, timeout(100)).add("Test");
    

9. Mocking Constructors (PowerMock Integration)

  • Mockito itself doesn’t directly mock constructors, but can be combined with PowerMock for mocking constructors, static methods, and private methods.
See also  What is Socket Programming in Java

10. Annotations for Mockito

  • @Mock: Used with @RunWith(MockitoJUnitRunner.class) or MockitoExtension to automatically create mocks.
  • @InjectMocks: Automatically injects mock dependencies into the class being tested.
  • @Captor: Automatically initializes ArgumentCaptor fields.

Example:

@Mock
List<String> mockList;

@InjectMocks
MyService myService;

@Captor
ArgumentCaptor<String> captor;

These are some of the common methods and features in Mockito, allowing you to create mocks, define behaviors, verify interactions, and more.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x