Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding Mockito 5.0.0: A Comprehensive Guide

Tech May 14 2

In the context of unit testing, Mock refers to the process of creating and utilizing mock objects to replace actual dependencies for testing purposes.

Mock, Stub, and Verify

1. Creating a Mock Object

// Create a mock object
List mockList = Mockito.mock(List.class);

2. Stubbing Behavior

// Define behavior
Mockito.when(mockList.get(0)).thenReturn("first");
Mockito.when(mockList.get(1)).thenThrow(new RuntimeException());

  • For any method with a return value, a mock object will provide a default return value.
  • Stubs can be overridden.
  • The last stubbing takes precedence.

3. Verifying Interactions

// Verify interactions
Mockito.verify(mockList).add("one");
Mockito.verify(mockList).clear();

Alternative Mock Creation Methods

Annotations like @Mock, @Spy, @Captor, and @InjectMocks can be used for mock creation, requiring initialization with MockitoAnnotations.openMocks().

Advanced Stubbing Techniques

1. Parameter Matching

Use ArgumentMatchers for flexible parameter matching.

2. Throwing Exceptions from Void Methods

Mockito.doThrow(new RuntimeException()).when(mockList).clear();

3. Chained Stubs

Mockito.when(mock.someMethod("param"))
       .thenThrow(new RuntimeException())
       .thenReturn("result");

4. Stubbing with Callbacks

Mockito.when(mock.someMethod(Mockito.anyString()))
       .thenAnswer(invocation -> {
           Object[] args = invocation.getArguments();
           return "called with: " + Arrays.toString(args);
       });

5. Using doReturn/doThrow/doAnswer/doNothing/doCallRealMethod

These method are used for stubbing void methods and spy objects.

6. Customizing Default Return Values

List<string> smartNullList = Mockito.mock(List.class, Mockito.RETURNS_SMART_NULLS);
smartNullList.get(0).length(); // No NullPointerException
</string>

7. Partial Mocking with Spy

List spyList = Mockito.spy(new LinkedList());
Mockito.when(spyList.size()).thenReturn(100);
spyList.add("item");
System.out.println(spyList.get(0)); // Outputs "item"
System.out.println(spyList.size()); // Outputs 100

Verification Techniques

1. Verifying Invocation Counts

Mockito.verify(mockList, Mockito.times(3)).add("three times");
Mockito.verify(mockList, Mockito.never()).add("never happened");

2. Verifying Invocation Order

InOrder inOrder = Mockito.inOrder(mockList);
inOrder.verify(mockList).add("one");
inOrder.verify(mockList).add("two");

3. Verifying No More Interactions

Mockito.verifyNoMoreInteractions(mockList);

4. Capturing Arguments

ArgumentCaptor<Integer> captor = ArgumentCaptor.forClass(Integer.class);
Mockito.verify(mockList, Mockito.times(2)).get(captor.capture());
System.out.println(captor.getAllValues()); // Outputs captured values

5. Timing Verification

Mockito.verify(mock, Mockito.timeout(100)).someMethod();

Special Operations

1. Resetting Mocks

Mockito.reset(mockList);

2. Validating Mockito Usage

Mockito.validateMockitoUsage();

3. BDD Style Testing

List<String> bddMockList = Mockito.mock(List.class);
Mockito.BDDMockito.given(bddMockList.get(0)).willReturn("value");
String result = bddMockList.get(0);
Assert.assertEquals("value", result);

4. Making Mocks Serializable

List serializableMock = Mockito.mock(List.class, Mockito.withSettings().serializable());

5. One-Line Mock Creation and Stubbing

Car car = Mockito.when(Mockito.mock(Car.class).startEngine()).thenReturn(true).getMock();

6. Ignoring Stubbed Method Calls

Use Strictness.STRICT_STUBS to ignore verified stubs.

7. Mock Details

MockingDetails details = Mockito.mockingDetails(mockList);
System.out.println(details.printInvocations());

8. Using Delegates

List<String> delegateList = Mockito.mock(List.class, AdditionalAnswers.delegatesTo(realList));

9. Custom Mock Generation with MockMaker

Implement custom mock generation using MockMaker.

10. Deep Stubbing

List<Line> deepMockList = Mockito.mock(List.class, Mockito.RETURNS_DEEP_STUBS);
Line line = deepMockList.iterator().next();

11. Enabling Annotations

  • Use @RunWith(MockitoJUnitRunner.class).
  • Call MockitoAnnotations.openMocks(this) in @Before.
  • Use MockitoJUnit.rule().

12. Plugin Control

Control plugin usage through PluginSwitch.

13. Custom Verification Messages

Mockito.verify(mock, Mockito.description("Custom message")).someMethod();

14. Using ArgumentMatchers in Stubbign and Verification

Mockito.doReturn("value").when(mockList).get(Mockito.argThat(i -> i < 3));

15. Simplifying doAnswer with AdditionalAnswers

Mockito.doAnswer(AdditionalAnswers.answerVoid((String param, Callback cb) -> cb.receive("dummy")))
       .when(mock).execute(Mockito.anyString(), Mockito.any(Callback.class));

Advanced Features

1. Mockito Extensions

Explore advanced API for framework integration.

2. Strict Mockito

Enable strict mode for debugging.

3. Integration with Spring

Resolve conflicts between Mockito and Spring proxies.

4. Mockito Sessions

Use MockitoSession as an alternative to MockitoRule.

5. Lenient Stubs and Mocks

Mockito.lenient().when(mock.someMethod()).thenReturn("value");

6. Memory Leak Prevention

@After
public void clearMocks() {
    Mockito.framework().clearInlineMocks();
}

7. Mocking Static and Constructor Methods

try (MockedStatic<Foo> mocked = Mockito.mockStatic(Foo.class)) {
    mocked.when(Foo::method).thenReturn("mockedValue");
}

8. Parameterless Mock Creation

Foo foo = Mockito.mock(Foo.class);
Bar bar = Mockito.spy(Bar.class);

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.