Powermock 在模拟私有方法时抛出 InvalidUseOfMatchersException

Powermock throws InvalidUseOfMatchersException when mocking private method

我是 Powermock 的新手。昨天我看了一个关于使用 Powermock 的视频,我按照他们的代码在下面有一个演示测试程序。当我运行测试

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);
    }
}

在下面的日志中抛出异常

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.

我对 Mockito 有一些基本了解,代码有点类似于 Mockito 单元测试(Mockito.spy 和 Mockito.when),但没有按预期工作。我不知道代码有什么问题,为什么会抛出异常 InvalidUseOfMatchersException。请帮帮我,谢谢。

您的代码缺少@PrepareForTest。 Powermock 必须操纵目标模拟的字节码 class,因此您必须提供它的路径。

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

此处ArgumentMatchers.any(String.class) 而是使用 ArgumentMatchers.anyString()