Explain Codes LogoExplain Codes Logo

Mockito matcher and array of primitives

java
mockito
unit-testing
argument-matchers
Anton ShumikhinbyAnton Shumikhin·Oct 22, 2024
TLDR

Stubbing with Mockito and an array of primitives? No problem! Use any() in conjunction with AdditionalMatchers.aryEq(). Here's a practical example:

import static org.mockito.Mockito.*; import static org.mockito.AdditionalMatchers.aryEq; // Your test method: int[] perfectSquareNumbers = {1, 4, 9}; // Because they're just square-dorable! when(mock.someMethod(aryEq(perfectSquareNumbers))).thenReturn(someValue);

Note: Stick with aryEq() for efficient and hassle-free array matching that compares values, not references.

How to Tackle Any Array

For those days when the specific contents of the array don't matter, any() comes to the rescue:

import static org.mockito.ArgumentMatchers.any; when(mock.mysteriousMethod(any(byte[].class))).thenReturn(someValue); // Nothing "byte" us yet!

When Precision is Key - Array Verification

When an array of exact values is the game, aryEq() is the name:

import static org.mockito.Mockito.verify; verify(mock).specialMethod(aryEq(new byte[]{0x10, 0x20})); // A couple of hex "friends"

Crafting Custom Matchers

Custom matchers aren't completely forbidden, but they can get complex and tedious for primitive arrays. Keep it simple where possible with good old aryEq(), and remember the order of verify calls doesn't affect your test outcome:

verify(mock).awesomeMethod(aryEq(new byte[]{0x01, 0x02})); // The power of verified consumption verify(mock).coolMethodTwo(aryEq(new byte[]{0x03, 0x04})); // Because two's company!

Stubbing Deep With Complex Matchers

Deep stubbing is when things get intense. Matchers.refEq could be an alternative to aryEq(), particularly when dealing with arrays hiding within nested objects:

import static org.mockito.Mockito.RETURNS_DEEP_STUBS; when(mock.someMethod().getNestedByteArr()).thenReturn(someNestedArr); // All the way down the rabbit hole!

When Arrays Get Complex

Array handling could get dicey with default values, large arrays, or complex data structures. Use ArgumentCaptor or custom argument matchers in these situations to tailor the behavior and ensure smooth performance of tests.