MockedStatic with arguments says "Misplaced or misused argument matcher detected"

799 Views Asked by At

I have one class where one public non-static method executes a static method call inside requires to mock static when I tried to test in junit with mockito.

What did i do wrong?

class DummyClass {

    public boolean filter(CharSequence source) {
        return Character.isHighSurrogate(source.charAt(7));
    }
}

@Test
public void testDummyCharacterMockedStatic() {
   try (MockedStatic<Character> mocked = Mockito.mockedStatic(Character.class)) {
       CharSequence source = "안녕하세요 세계";
       mocked.when(() -> Character.isHighSurrogate(anyChar())).thenReturn(true);
       DummyClass d = new DummyClass();
       assertTrue(d.filter(source));
   }
}

Error shows the following >>>>

Misplaced or misused argument matcher detected here:

-> at DummyTest.lambda$testDummyCharacterMockedStatic$0(DummyTest.java:37)

You cannot use argument matchers outside of verification or stubbing. Examples of correct usage of argument matchers: when(mock.get(anyInt())).thenReturn(null); doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject()); verify(mock).someMethod(contains("foo"))

This message may appear after an NullPointerException if the last matcher is returning an object like any() but the stubbed method signature expect a primitive argument, in this case, use primitive alternatives. when(mock.get(any())); // bad use, will raise NPE when(mock.get(anyInt())); // correct usage use

Also, this error might show up because you use argument matchers with methods that cannot be mocked. Following methods cannot be stubbed/verified: final/private/equals()/hashCode(). Mocking methods declared on non-public parent classes is not supported.

1

There are 1 best solutions below

0
On

No possible for the types we don't own

"Character" is a type from "java.lang.*" package

Caveat

The inline mock maker is an optional feature of Mockito.

Mockito includes this note in the JavaDoc for Mockito.mockStatic.

Note: We recommend against mocking static methods of classes in the standard library or classes used by custom class loaders used to executed the block with the mocked class. A mock maker might forbid mocking static methods of know [sic] classes that are known to cause problems. Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not explicitly forbidden.

The error messages issued by Mockito.mockStatic can be broad and confusing. The static mocking of low-level standard library classes can be unreliable and have unpredictable effects. It may take some experimentation to fine-tune use of this powerful feature.

Ref: https://site.mockito.org/ > "More"

Remember

  • Do not mock types you don’t own
  • Don’t mock value objects
  • Don’t mock everything
  • Show love with your tests!