Search code examples
javaunit-testingmockitopowermockito

Powermock throws InvalidUseOfMatchersException when mocking private method


I'm new to Powermock. Yesterday I watched a video about using Powermock, I follow their code and have a demo test program below. When I run the test

package myPackage;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
public class Test1{
    @Test
    public void testPrivateMethod() throws Exception {
        DemoService mockDemoService = PowerMockito.spy(new DemoService());
        PowerMockito.when(
                mockDemoService,
                "privateMethod",
                ArgumentMatchers.any(String.class)
        ).then(invocation -> invocation.getArgument(0) + "_private_mock");
        Assert.assertEquals(mockDemoService.dependentMethod("LoveTest"), "3000LoveTest_private_mock");
    }
}

class DemoService {
    private String privateMethod(String input) {
        return input + "_private";
    }
    public String dependentMethod(String input) {
        return 3000 + privateMethod(input);
    }
}

It throw exception in the log below

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Misplaced or misused argument matcher detected here:

-> at myPackage.Test1.testPrivateMethod(Test1.java:19)

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.

I have some basic knowledge about Mockito, the code is somewhat similar to Mockito unit test (Mockito.spy and Mockito.when) but not work as expected. I don't know what's wrong with the code, why the exception InvalidUseOfMatchersException is thrown. Please help me, thank you.


Solution

  • Your code is missing @PrepareForTest. Powermock has to manipulate the byte-code of target mocking class, so you have to provide a path to it.

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(DemoService.class)
    public class Test1{
        ...