我有一个使用Powermock + Mockito抑制实用程序类中的静态方法的类。它在Powermock 1.6.2和Mockito 1.10.19上可以正常工作,但是我的任务是迁移到Java 10(JRE:我们仍在使用Java 8进行编译),所以我已经迁移到Powermock 2(当前处于beta版) )和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();
}
}
}
我假设要么对匹配器可用于匹配存根静态方法中的参数的方式进行了一些更改,要么这种方法永远不起作用,并且在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