繁体   English   中英

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 必须操作目标模拟类的字节码,因此您必须提供它的路径。

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

这里 ArgumentMatchers.any(String.class) 改为使用 ArgumentMatchers.anyString()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM