0

I am trying to use PowerMockito to mock a private class like this:

PowerMockito.when(spyClass, "privateMethod", anyString()).thenReturn(returnList);

I have these two annotations above the test method:

@Test
@PrepareForTest(CartItemRepository.class)

And these above the class:

@ExtendWith(MockitoExtension.class)
@RunWith(PowerMockRunner.class)

There are no previous method calls (stubbed or otherwise) in the test method that could be interfering.

But, I am getting an error related to incorrect use of argument matchers.

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"))

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.

I am using the when method of PowerMockito (and not regular Mockito) but the 2nd error paragraph makes it seem like mocking private methods is still not possible.

I'm not sure what I'm doing wrong here.

  • Welcome to StackOverflow! Can you please show us your `@RunWith` and `@PrepareForTest` class annotations, and whether you have any usage of (Power)Mockito or matchers above the line you posted? You can also call [`Mockito.validateMockitoUsage()`](https://www.javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#validateMockitoUsage()) immediately before your call to `PowerMockito.when`, since [argument matchers are stateful](https://stackoverflow.com/q/22822512/1426891) and there's a chance a previous call is affecting the one you pasted here. – Jeff Bowman Jul 12 '22 at 18:03
  • @JeffBowman Thanks! I made some edits with more information on the issue. Please let me know if anything else is needed? – Cydni Turner Jul 12 '22 at 20:22

0 Answers0