gpt4 book ai didi

java - 在 Mockito 2 中 stub 静态方法会抛出 InvalidUseOfMatchersException

转载 作者:行者123 更新时间:2023-11-30 06:13:53 25 4
gpt4 key购买 nike

我有一个类,我使用 Powermock + Mockito 来抑制实用程序类中的静态方法。它与 Powermock 1.6.2 和 Mockito 1.10.19 配合得很好,但我的任务是迁移到 Java 10(JRE:我们仍在使用 Java 8 进行编译),所以我已经迁移到 Powermock 2(目前处于测试阶段) )和 Mockito 2.16.1。现在,我一直得到 org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here

一个简单的例子,MyMockito.java:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.lang.reflect.Method;

import static org.mockito.Mockito.any;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.support.membermodification.MemberMatcher.method;
import static org.powermock.api.support.membermodification.MemberModifier.suppress;

@RunWith(PowerMockRunner.class)
@PrepareForTest(StringMeasurer.class)
public class MyMockito {
@Test
public void testSuppressMethod() throws Exception {
spy(StringMeasurer.class);
Method measure = method(StringMeasurer.class, "measure", String.class);
suppress(measure);
when(StringMeasurer.class, measure)
.withArguments(any(String.class))
.thenReturn(10);
System.out.println(StringMeasurer.measure("Hello"));
}

和 StringMeasurer.java:

    public class StringMeasurer {
private StringMeasurer() {}
public static int measure(String s) {
return s.length();
}
}
}

我假设要么对如何使用匹配器来匹配 stub 静态方法中的参数进行了一些更改,要么这应该永远在 Mockito 2 中不起作用并以某种方式通过(或者这可能是 Powermock beta 中的一个错误)。谁能告诉我我做错了什么?

最佳答案

PowerMock 2.0.0-beta.5的工作解决方案:

import static org.mockito.ArgumentMatchers.any;
import static org.powermock.api.mockito.PowerMockito.when;

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

@RunWith(PowerMockRunner.class)
@PrepareForTest(StringMeasurer.class)
public class MyMockito {
@Test
public void testSuppressMethod() throws Exception {
PowerMockito.mockStatic(StringMeasurer.class);
when(StringMeasurer.measure(any(String.class))).thenReturn(10);
System.out.println(StringMeasurer.measure("Hello"));
}
}

更多详细信息可以参见PowerMock官方文档:Mocking Static Method

关于java - 在 Mockito 2 中 stub 静态方法会抛出 InvalidUseOfMatchersException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49659016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com