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.